四个'东西'括号中的工作是Javascript

How does a for-loop with four 'things' in the parenthesis work i Javascript?

本文关键字:工作 Javascript 东西 四个      更新时间:2023-09-26

我在这里遇到了一些代码https://stackoverflow.com/a/2922778/2176900,它们是这样开始的:

for (i = 0, j = nvert-1; i < nvert; j = i++) {...`

,我不明白它是怎么做的,当它有四个东西在括号内(" I = 0", "j = nvert-1", " I <"answers"j = i++")。显然,我一直在谷歌上搜索这个问题,但似乎找不到任何答案。我敢肯定,如果我知道括号里的东西叫什么,我会很高兴的。

谢谢

它没有四样东西;还有三个

  • 循环前语句
    i = 0, j = nvert-1

  • 迭代条件
    i < nvert

  • 迭代后动作
    j = i++

这个预循环语句实际上应该是:
var i = 0, j = nvert-1

请记住,我们可以在一个声明中声明多个变量。

除了@LightnessRacesinOrbit和@basilikum给出的优秀答案之外,我还提供了一个建议,当我看到像这样不寻常的for循环时,我觉得很有帮助:将其分解为更原始的形式。

任意for循环:

for( initialize; condition; advance ) {
    // loop body here
}

可以转换成等价的while循环:

initialize;
while( condition ) {
    // loop body here
    advance;
}

所以你找到的循环是:

for ( i = 0, j = nvert-1;  i < nvert;  j = i++ ) {
    // loop body here
}

可以写成:

i = 0,  j = nvert - 1;
while( i < nvert ) {
    // loop body here
    j = i++;
}

现在我们可以把它分解成更简单的步骤。

正如@basilikum指出的,第一行:

i = 0,  j = nvert - 1;

等于:

i = 0;
j = nvert - 1;

和循环的最后一行:

    j = i++;

等于:

    j = i;
    i = i + 1;

所以把它们放回代码中我们最终得到:

i = 0;
j = nvert - 1;
while( i < nvert ) {
    // loop body here
    j = i;
    i = i + 1;
}

这比原来的for循环更冗长,但如果原来的循环令人困惑,它可能更容易考虑。

除了用户Lightness Races in Orbit已经解释过的语法之外,使用这种循环的原因很可能是为了循环遍历数组并总是访问两个相邻的项。

var list = [1,2,3,4],
    nvert = list.length;
for (i = 0, j = nvert-1; i < nvert; j = i++) {
    //...
}

第一次迭代:

i = 0; //index of first item
j = nvert-1; //indext of last item

以下迭代:

j = i;     //j becomes the old value of i
i = i + 1; //i gets incremented by one

如果考虑数组[1,2,3,4],那么ij将代表每次迭代的以下项目:

//first iteration
i => 1
j => 4
//second iteration
i => 2
j => 1
//third iteration
i => 3
j => 2
//fourth iteration
i => 4
j => 3