函数工作,但当随机数变得太高时,第53个未定义元素被添加到数组中。
function shuffle(deck , shuffles) {
for(let i = 0; i < shuffles; i++) {
let first = Math.floor(Math.random() * 53);
let secound = Math.floor(Math.random() * 53);
let fShuffle = deck[first];
let sShuffle = deck[secound];
deck[first] = sShuffle;
deck[secound] = fShuffle;
}
return deck;
}它打乱了所有东西,除了一个未定义的元素偷偷进入,我不确定如何摆脱它。
发布于 2019-07-14 12:35:43
由于deck将有52个元素,因此您的索引将来自0 to 51,以防您的Math.floor(Math.random() * 53)结果为52,因此您将访问未定义的deck[52]
您需要将其更改为
Math.floor( Math.random() * 52 )发布于 2020-07-18 23:33:08
我的代码创建了一个随机数,然后乘以卡片组的长度,得到一个特定的索引,然后将该索引的值添加到一个新的数组中。
for (shuffled_deck.length = 0; shuffled_deck.length < 52 ; shuffled_deck) {
// Creates a random number and multiplies it by length of deck.
var chosencard = Math.ceil(Math.random() * numcards)
if (chosencard == 52) {
chosencard = 0
}
var addcard = totaldeck[chosencard]
// Uses the random number to be an index in the totaldeck array
if (shuffled_deck.includes(addcard)) {
}
else {
shuffled_deck.push(addcard) // Adds the value into the new shuffled deck array
}
}
console.log(shuffled_deck)希望这是有意义的。
https://stackoverflow.com/questions/57024605
复制相似问题