这里有一些用于随机化数组的javascript.有人可以一点一点地解释它是如何工作的

Here's a bit of javascript used to shuffle, or randomize, an array. Can someone explain it piece by piece how it works?

本文关键字:一点 工作 解释 何工作 随机化 用于 数组 javascript 这里      更新时间:2023-09-26
for(var j, x, i = answerArr.length; i; j = parseInt(Math.random() * i), x = answerArr[--i], answerArr[i] = answerArr[j], answerArr[j] = x);
        for(var t = 0; t < answerArr.length; t++)
        {
            $("#kc_answers").append('<li><span class="kc_answer_span">' + $(answerArr[t]).find('aText').text() + '</span></li>');
        }

有人可以一步一步地解释代码的不同部分在做什么吗?

这似乎是一个非常常见的代码,进行了一些更改以随机顺序将数组的一部分附加到div。我理解了很多javascript和jquery,但我不太了解这一点。

我认为这对其他人也很有用,因为这段代码正在洗牌一个数组并将这些片段吐出到 html 中。似乎这可能是一种常见的需求。

这可以重写为:

    // loop from arrayArr.length - 1 to 0
    for (var randomIndex, temp, i = answerArr.length - 1; i >= 0; i--)
    {
        // get a random index in the array.
        randomIndex = Math.floor(Math.random() * i);
        // put the current index in a temporary variable
        temp = answerArray[i];
        // assign the random index to the current index
        answerArr[i] = answerArr[randomIndex];
        // assign the temporary variable to the random index
        answerArr[randomIndex] = temp;
    }
    // now output the new shuffled array
    for(var t = 0; t < answerArr.length; t++)
    {
        $("#kc_answers").append('<li><span class="kc_answer_span">' + $(answerArr[t]).find('aText').text() + '</span></li>');
    }

更新

关于没有身体的for loop,基本上这就是for loop的工作原理:

for (run what is in here once;
     evaluate this each time after the next statement and the body... if it evalutes to false then exit;
     run what is here each time after the body)
{
    // run this until the second statement is false
}

所以原始代码的作者是这样的:

for (run this once;
     evaluate this expression each time;
     forget having a body, just put everything in here!!); 
这是一个

费舍尔-耶茨洗牌。确实很常见。