所以我正在阅读有关改组数组的内容。然后我遇到了this script :
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;
};
当我仔细观察时,for
根本没有任何 {}
!但它正在发挥作用,就像变魔术一样。我很好奇它是如何工作的。 (还有一堆逗号。)
最佳答案
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
这可以用更易读的形式表示为:
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;
}
作为 while 循环,这可能是:
var j, x, i = o.length;
while (i) {
j = parseInt(Math.random() * i);
x = o[--i];
o[i] = o[j];
o[j] = x;
}
关于javascript - 没有任何 {} 的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11008030/