gpt4 book ai didi

javascript - 如何在 JavaScript 中多次打乱数组

转载 作者:行者123 更新时间:2023-11-29 20:50:19 25 4
gpt4 key购买 nike

<分区>

我一直在阅读关于在 JavaScript 中对数组执行洗牌的最佳方法,并且遇到了 Fisher-Yates 模型(在 this articlethis article 中)。我已经尝试使用文章中指向的两个示例函数,但是当我想多次打乱数组并将不同的结果分配给两个不同的变量时,它们最终会完全相同。

    function shuffle(array) {
var i = 0,
j = 0,
temp = null

for (i = array.length - 1; i > 0; i -= 1) {
j = Math.floor(Math.random() * (i + 1))
temp = array[i]
array[i] = array[j]
array[j] = temp
}
return array;
}

var deck = ["bat", "black-cat", "blood", "bone", "brain", "broom", "candle", "candy", "castle", "cauldrom", "coffin", "costume", "death", "devil", "fish-bone", "full-moon", "ghost", "grave", "grave-yard", "half-moon", "horror", "lantern", "magic", "monster", "owl", "pumpkin", "skull", "spider", "spider-web", "tree", "tree-2", "witch", "witch-hat", "zombie-1", "zombie-2"];



var playerHand = shuffle(deck);
var computerHand = shuffle(deck);

console.log(playerHand);
console.log(computerHand);

在控制台 playerHand 返回:

["castle", "costume", "coffin", "candy", "blood", "death", "horror", "skull", "spider", "broom", "owl", "tree", "spider-web", "pumpkin", "grave", "devil", "brain", "ghost", "witch-hat", "magic", "bat", "black-cat", "full-moon", "tree-2", "cauldrom", "bone", "grave-yard", "half-moon", "zombie-1", "lantern", "monster", "zombie-2", "candle", "fish-bone", "witch"]

computerHand 返回:

["castle", "costume", "coffin", "candy", "blood", "death", "horror", "skull", "spider", "broom", "owl", "tree", "spider-web", "pumpkin", "grave", "devil", "brain", "ghost", "witch-hat", "magic", "bat", "black-cat", "full-moon", "tree-2", "cauldrom", "bone", "grave-yard", "half-moon", "zombie-1", "lantern", "monster", "zombie-2", "candle", "fish-bone", "witch"]

这可能非常简单,但我很难过。我认为再次调用该函数会返回不同的结果。

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