我的shuffle函数以单数形式工作,但是将多个调用组合成一个函数时,它会中断

问题描述

这里我必须缺少一些基本原理,但是函数shuffle可以按预期工作,但是当我尝试在另一个函数中多次调用任何函数时,第一次调用会导致数组中充满52个未定义的条目。

function shuffle(array) {
    let newDeck = [];

    for (i=52; i>0; i--) {
        let randomPick = Math.floor((Math.random() * array.length));

        newDeck.push(array[randomPick]);
        deck.splice(randomPick,1);
    }
    deck = newDeck;
    console.log(deck);
}

function fullShuffle(cards) {
    shuffle(cards);
    shuffle(cards);
}

解决方法

该代码在问题中并不完整,但似乎deck是一个全局变量,您还可以将其作为参数传递给fullShuffle。问题是deck.splice在一次调用shuffle中就完全清空了该数组,因此,如果再次使用该deck并将其通过fullShuffle传递给{{1}再一次,},您传递的是一个空数组,并且所有52次迭代都未定义shuffle(因为如果我对您其余部分的假设正确,则array[randomPick]array的引用相同)

如果您想通过这种方式实施改组,则:

  • 请勿在该函数内使用全局变量
  • 仅依靠函数获取的参数
  • 获取该数组的副本,以便您可以愉快地拼接而不影响调用方的数组
  • 将经过改组的数组返回给调用方

代码:

deck

尽管对于人类洗牌来说,将同一副牌洗牌两次是有意义的,但是对于这样的功能,两次调用它几乎没有意义。就像您不信任随机随机播放的功能一样。

还要注意,function shuffle(array) { let newDeck = []; array = [...array]; // take copy! for (i=52; i>0; i--) { let randomPick = Math.floor((Math.random() * array.length)); newDeck.push(array[randomPick]); array.splice(randomPick,1); } console.log(newDeck); return newDeck; // return it. } function fullShuffle(cards) { cards = shuffle(cards); // capture the returned,shuffled array cards = shuffle(cards); return cards; // return to caller } // can be called like this: var deck = [ "ac","2c","3c","4c","5c","6c","7c","8c","9c","10c","jc","qc","kc","ad","2d","3d","4d","5d","6d","7d","8d","9d","10d","jd","qd","kd","ah","2h","3h","4h","5h","6h","7h","8h","9h","10h","jh","qh","kh","as","2s","3s","4s","5s","6s","7s","8s","9s","10s","js","qs","ks" ]; deck = fullShuffle(deck); 有更好的实现。看看here,您会找到Durstenfeld算法的实现。