关于JavaScript for()循环伏都教 [英] Regarding JavaScript for() loop voodoo

查看:72
本文介绍了关于JavaScript for()循环伏都教的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经有一段时间了,循环的可以 以下列格式存在:

I was for quite some time under the impression that a for loop could exist solely in the following format:

for (INITIALIZER; STOP CONDITION; INC(DEC)REMENTER)
 {
    CODE
 }

但是,大多数绝对并非如此;看一下 Fisher-Yates Shuffle 的JavaScript实现:

This is, however, most definitely not the case; take a look at this JavaScript implementation of the Fisher-Yates Shuffle:

shuffle = function(o)
 {
    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循环声明中,这个世界是如何进行的?我的意思是......它甚至没有打开支架!所有的魔法都是在中为语句完成就在那里。如果有人可以提供一个相对彻底的解释来说明世界上这个伏都教正在做它做什么,那将是绝对美妙的。非常感谢。

This little snippet completely blows my mind; how in the world is so much going on inside a simple for loop declaration? I mean... it doesn't even open a brace! All of the magic is being done right there inside the for statement. It'd be absolutely wonderful if somebody could provide a relatively thorough explanation as to how in the world this voodoo is doing what it does. Much appreciated in advance.

推荐答案

for循环的广义格式(不是for-in循环)是

The generalized format of a for loop (not a for-in loop) is

for ( EXPRESSION_1 ; EXPRESSION_2 ; EXPRESSION_3 ) STATEMENT

第一个EXPRESSION_1 通常用于初始化循环变量,EXPRESSION_2是循环条件,而EXPRESSION_3 通常是增量或减量操作,但没有规则说他们必须表现得那样。它相当于以下while循环:

The first EXPRESSION_1 is usually used to initialize the loop variable, EXPRESSION_2 is the looping condition, and EXPRESSION_3 is usually an increment or decrement operation, but there are no rules that say they have to behave like that. It's equivalent to the following while loop:

EXPRESSION_1;
while (EXPRESSION_2) {
    STATEMENT
    EXPRESSION_3;
}

逗号只是一个将两个表达式组合成一个表达式的运算符, value是第二个子表达式。它们用于for循环,因为每个部分(以分号分隔)需要是单个表达式,而不是多个语句。没有理由(除了可能在文件中保存一些空间)来写这样的for循环,因为这是等价的:

The commas are just an operator that combines two expressions into a single expression, whose value is the second sub-expression. They are used in the for loop because each part (separated by semicolons) needs to be a single expression, not multiple statements. There's really no reason (except maybe to save some space in the file) to write a for loop like that since this is equivalent:

shuffle = function(o) {
    var j, x;
    for (var i = o.length; i > 0; i--) {
        j = parseInt(Math.random() * i);
        x = o[i - 1];
        o[i - 1] = o[j];
        o[j] = x;
    }
    return o;
};

这篇关于关于JavaScript for()循环伏都教的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆