这个问题在这里已有答案:
我一直在阅读关于在JavaScript中对数组执行shuffle的最佳方法,并且遇到了Fisher-Yates模型(在this article和this 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"]
这可能非常简单,但我很难过。我认为再次调用该函数会返回不同的结果。
你的函数在那里“就地”改组数组 - 也就是说,它正在改变数组而不是创建一个新的数组。
因为在第二次调用中它是相同的数组,所以你“丢失”了第一个shuffle结果。
要解决此问题,请创建数组的克隆:
var playerHand = shuffle(deck.slice());
var computerHand = shuffle(deck.slice());