我一直在阅读有关在JavaScript中对数组执行随机播放的最佳方法,并遇到了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"]
这可能非常简单,但是我很困惑。我以为再次调用该函数会返回不同的结果。
答案 0 :(得分:2)
您的函数在此处“随机”重组数组-也就是说,它正在更改数组而不是创建新数组。
由于第二个调用中的数组相同,所以您“失去”了第一个混洗结果。
要解决此问题,请创建数组的副本:
var playerHand = shuffle(deck.slice());
var computerHand = shuffle(deck.slice());