gpt4 book ai didi

Javascript - 从数组中选择随机变量但仅一次

转载 作者:行者123 更新时间:2023-12-03 02:04:31 24 4
gpt4 key购买 nike

是否可以在数组中只选择一次变量?我制作了一个点击功能,每次点击时它都会给我一个随机报价。我该如何使其不会再次选择相同的变量?

我想要做的是,只要有更多“看不见的”报价,就可以多次单击按钮,而不会再次遇到相同的报价。 (我没有在代码片段中包含所有原始引用)。

var quotes = [
'Catsy',
'Jope',
'Nope',
'Hey',

]

function newQuote() {
var randomNumber = Math.floor(Math.random()*(quotes.length));
document.getElementById('quoteDisplay').innerHTML = quotes[randomNumber];
}
html { 
background: url(bild.jpg)
no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
h1 {
text-align: center;
color: rgb(77, 77, 77);
font-size: 120px;
font-family: "Courier New", monospace;
}
div {
color: white;
text-align: center;
font-family: "Courier New", monospace;
justify-content: center;
font-size: 45px;
margin-right: 400px;
margin-left: 400px;
}
button {
height:30px;
width:150px;
margin: 300px -100px;
position: absolute;
top:50%;
left:50%;
font-size: 16px;
font-family: "Courier New", monospace;
}
<!DOCTYPE html>
<html>
<head>
<title>Bop</title>
<link rel="stylesheet" type="text/css" href="fp.css">
</head>

<body>
<h1>Mjao</h1>

<div id="quoteDisplay">

</div>

<button onclick="newQuote()">Another one!</button>


<script src="fp.js"></script>

</body>

</html>

最佳答案

执行此操作的一个简单方法是打乱数组的副本,然后迭代它。有关如何随机播放的信息,请参阅此答案:

How to randomize (shuffle) a JavaScript array?

关于Javascript - 从数组中选择随机变量但仅一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49861240/

24 4 0
文章推荐: javascript - 标记上存在未知属性 `selectable`。在 Material UI 中