[英]Conditional statement in a for loop simple as i
I found these lines of code in a library made to listen to touch events : 我在用来监听触摸事件的库中找到了以下代码行:
for ( var i = elements.length; i; i-- ) {
iterator( elements[ i - 1 ], elements );
}
It surprised me for a second. 这让我感到惊讶。 I understand the code this way : i is an integer positive or null and the conditional statement is if i positive. 我以这种方式理解代码:i为整数正数或null,条件语句为i为正数。
Do I understand right ? 我明白吗? Does i return false when i==-1 ? 当i ==-1时我会返回false吗? Or did i miss something (like it's possible to write a for loop without a conditional statement) ? 还是我错过了某些事情(例如无需条件语句就可以编写for循环)?
The conditional is essentially if( i) proceedToNextIteration();
条件本质上是if( i) proceedToNextIteration();
As numbers go, only zero is falsy and would fail the check. 随着数字的增加,只有零是虚假的,并且会导致检查失败。 -1
would be true in the above condition. 在上述条件下, -1
为真。
For this reason, I'd rewrite that code as: 因此,我将代码重写为:
for( var i = elements.length-1; i >= 0; i--) {
iterator( elements[i], elements);
}
It's much more explicit about its final condition. 它的最终状态要明确得多。
This is the structure of the for
statement in Javascript: 这是Java 语言中for
语句的结构:
for ([initialization]; [condition]; [final-expression])
statement
The statement you provided for ( var i = elements.length; i; i-- ) 您提供的语句(var i = elements.length; i; i--)
adheres to this syntax. 遵守此语法。 This is same as 这和
for(var i = 10; i!=0; i--)
Meaning loop from 10
( elements.length
) to 1
. 从10
( elements.length
)到1
含义循环。 Similar to looping from 1
to 10
. 类似于从1
循环到10
。
In Javascript, the condition i != 0
can be replaced with just i
. 在Javascript中,条件i != 0
可以仅用i
代替。
Meaning: 含义:
if(i != 0)
and 和
if (i)
are the same. 是相同的。 That is what is done in the condition part. 这就是在条件部分完成的操作。
Looping over elements of a list or array from max to 0 is helpful when removing items from it. 将列表或数组的元素从max循环到0有助于从列表或数组中删除项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.