实现Fisher-Yates洗牌循环是行不通的

Implementing a Fisher–Yates shuffle loop is not working

本文关键字:行不通 循环 Fisher-Yates 实现      更新时间:2023-09-26

我正试图实现Fisher-Yates洗牌,但是当我测试下面的代码时,它似乎没有循环。我想它在第一次之后就停止了。

function scrambleWord() {
    var letterArray = currentWord.split("");
    var m = letterArray.length, t, i;
    while (m) {
        x = Math.floor(Math.random() * m--);
        t = letterArray[m];
        letterArray[m] = array[i];
        array[i] = t;
    }
    scrambledWord = letterArray.join("");
}

array, icurrentWord在任何地方都没有定义:

function shuffleWord(word) {
  var array = word.split('');
  var m = array.length, t, i;
  // While there remain elements to shuffle…
  while (m) {
    // Pick a remaining element...
    i = Math.floor(Math.random() * m--);
    // And swap it with the current element.
    t = array[m];
    array[m] = array[i];
    array[i] = t;
  }
  return array.join('');
}

因为您没有定义currentWordarray

故障排除从浏览器的开发控制台开始。