javascript - 没有任何 {} 的 for 循环

标签 javascript

所以我正在阅读有关改组数组的内容。然后我遇到了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/

相关文章:

javascript - 有什么方法可以使用 Javascript 模拟鼠标悬停在特定元素上的特定 x/y 偏移量吗?

Javascript 在 RGBA 范围内放入 4 个整数

javascript - 预览图像而不上传到我的服务器

javascript - 像迪士尼 map 一样自定义 Google map 叠加层

javascript - Javascript 中的回调 ~ 如何在函数完成后触发事件?

javascript - ReactJS - MappleToolTip 未渲染

javascript - 无法使用 bootstrap 触发工具提示会出现错误

javascript - 浏览器检测

javascript - 检查代理对象是否被撤销

Javascript根据另一个索引重新索引数组