没有任何{}的for循环

Der*_*會功夫 5 javascript

所以我正在阅读关于改组阵列的内容.然后我遇到了这个脚本:

shuffle = function(o){ //v1.0
    for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};
Run Code Online (Sandbox Code Playgroud)

当我仔细观察时,for甚至根本没有{}!但它像魔术一样有效.我很想知道它是如何工作的.(还有一堆逗号.)

Chr*_*gan 10

以下内容for ()可以是任何声明; 可以是花括号的东西,也可以是单个表达式,也可以是空表达式.for (...);相当于for (...) {}.当然,这应该只与一个自然终止的for循环一起使用,否则你手上会有一个无限循环.

逗号实际上是二级分号; 它们主要用于单独的语句,但它们可以在for循环中工作(以及其他地方;这是对它们的非常草率的定义).

for (
     // initialisation: declare three variables
     var j, x, i = o.length;
     // The loop check: when it gets to ``!i``, it will exit the loop
     i;
     // the increment clause, made of several "sub-statements"
     j = parseInt(Math.random() * i),
     x = o[--i],
     o[i] = o[j],
     o[j] = x
)
    ; // The body of the loop is an empty statement
Run Code Online (Sandbox Code Playgroud)

这可以放在一个更易读的形式:

for (
     // initialisation: declare three variables
     var j, x, i = o.length;
     // The loop check: when it gets to ``!i``, it will exit the loop
     i;
     // note the increment clause is empty
) {
     j = parseInt(Math.random() * i);
     x = o[--i];
     o[i] = o[j];
     o[j] = x;
}
Run Code Online (Sandbox Code Playgroud)

作为while循环,可能是:

var j, x, i = o.length;
while (i) {
     j = parseInt(Math.random() * i);
     x = o[--i];
     o[i] = o[j];
     o[j] = x;
}
Run Code Online (Sandbox Code Playgroud)