问题描述
我正在阅读,我无法理解'for loop'所使用的概念
I was reading through this question, I am not able to grasp the concept used for the 'for loop'
通常,for循环的语法是 for(赋值,检查条件,增量){}
他们使用了for循环,但是没有条件检查,这是如何工作的?
Generally, syntax of for loop is for(assign value, check condition, increment){}
They have used the for loop but there is no condition checking, how does this work?
for(var i = arr1.length; i--;) {
if(arr1[i] !== arr2[i])
return false;
}
推荐答案
实际上,它是
for ([initialization]; [condition]; [final-expression])
其中所有三个表达式都是可选。
where all three expressions are optional.
在这种情况下, i -
是一个条件,当它达到 0
它是假的,并且循环停止。$
final-expression
是这里没有使用的。
In this case, i--
is a condition, when it reaches 0
it's falsy, and the loop stops.
The "final-expression"
is the one not used here.
var arr = [1, 2, 3, 4];
for (var i = arr.length; i--;) {
console.log(arr[i]);
}
for
语句将 i
的值设置为正整数,然后在每次迭代时评估条件,有效地递减我
直到达到数字是假的,当 i
达到零时发生。
The for
statement sets the value of i
to a positive integer, then on each iteration it evaluates the condition, effectively decrementing i
until it reaches a number that is falsy, which happens when i
reaches zero.
以下是如何在中跳过
循环中的表达式的其他一些示例
Here's some other examples of how to skip expressions in a for
loop
跳过初始化
var i = 0;
for (; i < 4; i++) {
console.log(i);
}
跳过条件
for (var i = 0;; i++) {
console.log(i);
if (i > 3) break;
}
跳过一切
var i = 0;
for (;;) {
if (i > 4) break;
console.log(i);
i++;
}
这篇关于没有条件检查的for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!