我正在创建一个战舰游戏,并且我正在尝试随机化计算机的船只。然而,它有时会多次随机化同一位置,从而在某些回合中创建的船只少于 8 艘。我尝试使用 indexOf 修复此问题,但无论如何更改代码,我似乎都无法使其工作。如果随机数字位于数组 ShipLocations 中,那么我想再次重新滚动该数字,直到它是与数组中的任何数字都不匹配的数字。有什么想法吗?
var shipLocations = [];
function randShips() {
for (i = 0; i < 8; i++) {
var randomize = Math.floor(Math.random() * 64 + 1);
if (shipLocations.indexOf(randomize) == true) {
var randomize = Math.floor(Math.random() * 64 + 1);
}
else {
shipLocations.push(randomize);
}
} //end of i loop
} //end of randShips()
randShips();
console.log(shipLocations);
编辑:因此,在尝试了一些答案之后,在测试了大约 100 次后,这似乎按应有的方式工作。
var shipLocations = [];
function randShips() {
while (shipLocations.length < 8) {
var randomize = Math.floor(Math.random() * 64 + 1);
while (shipLocations.indexOf(randomize) > -1) {
randomize = Math.floor(Math.random() * 64 + 1);
}
shipLocations.push(randomize);
}
}
randShips();
最佳答案
var shipLocations = [];
function randShips() {
while ( shipLocations.length < 8 ) {
var randomize = Math.floor(Math.random() * 64 + 1);
while ( shipLocations.indexOf(randomize) >= 0 ) {
randomize = Math.floor(Math.random() * 64 + 1);
}
shipLocations.push(randomize);
}
} //end of randShips()
randShips();
console.log(shipLocations);
关于javascript - 检查随机数是否在数组中,如果为真则再次随机化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26058607/