gpt4 book ai didi

javascript - 从 JavaScript 数组中随机选择不重复的项目

转载 作者:行者123 更新时间:2023-11-28 15:34:30 25 4
gpt4 key购买 nike

我试图从数组中获取一个随机数而不重复,但使用 var newx = Math.floor(Math.random() * array.length);确实随机化,但它是按长度而不是数组内部的内容进行的,因此它确实会重复。

<html>
<head>

</head>
<!-- <body> -->
<button onclick="myFunction()">Difficulty</button>
<p id="demo">here</p>
<p id="test"></p>
<script>



function myFunction() {

function shuffle(o){ //try this shuffle function
for(var j, g, t = o.length; t; j = Math.floor(Math.random() * t), g = o[--t], o[t] = o[j], o[j] = g);
return o;
};

var i; var l; var y; var n;
var newx; var newy;
var useranswer; var amountX; var largest;
var copyAmountX;
var mixAlot;

var x = parseInt(prompt("What is the first number?"+" "+"(up to 12)"));

if (x < 13) {
y = prompt("what is the second number?"+" "+"(choose up to 12)");
n = prompt("how many problems to be solved?");
amountX = []

// adds to an array equal to x (user input)
if (!amountX.length) {
for (var s = 0; s <= x; s++) {
amountX.push(s);
}
};
// just to let me know if it is working. Will be taken out.
alert(amountX);
largest = Math.max.apply(Math, amountX);
alert(largest);
alert(isNaN(x));
}
else {
alert("Refresh page and restart with numbers under 12")
};
if (y > 12 == true) {
alert("Refresh page and restart with numbers under 12")
};

i = 0;
l = amountX.length;
copyAmountX = amountX;
// where the core magic of everything happens.
while (x < 13 && y < 13 && i<n) {
newx = shuffle(copyAmountX);
newy = Math.floor(Math.random() * y);
useranswer = prompt("Multiply "+newx+" by "+newy)
if (useranswer == newx * newy) {
alert("Correct! problem "+(i+1)+" of "+n);
};
if (amountX == 0) {alert("You have completed your Difficulty! Good Game"); n = 0;
};
i++;
};
};
</script>


</body>
</html>

最佳答案

如果您尝试从数组中获取随机数,那么我会推荐一种不同的方法:复制数组,然后随机播放副本。

function shuffle(o){ //try this shuffle function
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};

这样,您就可以继续从打乱的数组中弹出元素;它们总是随机的,并且只出现一次。

<小时/>

现在关于你的代码,恐怕它有很多错误:...我删除了这部分

修复:

我更正了你的程序,现在它运行得很好。请仔细阅读并应用我在 javascript 中评论的更改。 Link

关于javascript - 从 JavaScript 数组中随机选择不重复的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26079643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com