这个语法是如何工作的?
erase: function(item){
for (var i = this.length; i--;) {
if (this[i] === item) this.splice(i, 1);
}
return this;
}
这个 (var i = this.length; i--;)
语法结构如何工作?
应该分为三个部分吗?在这种情况下是什么?
来自此处。
erase: function(item){
for (var i = this.length; i--;) {
if (this[i] === item) this.splice(i, 1);
}
return this;
}
How would this (var i = this.length; i--;)
syntactic construct work?
Should there be three sections? What is it in this case?
from here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
类 C 语言中的 for 循环由三部分组成:
然后,循环将转换为以下(大致)等效的循环(存在差异,但此处不相关):
因此初始化程序部分首先运行;那么只要条件保持为真,循环就会运行,并且在每次迭代结束时更新部分运行。它不一定是增量,但最常见的形式如下所示:
但是您可以在这些部分中写入您想要的任何内容,如果您在循环中执行的任何操作足以使循环正确运行,您也可以将它们留空,并且终止。因此,在您的情况下,由于
i--
是一个也更新i
的表达式,因此循环仅结合 condition 和 update< /em> 变为 1 并倒计时。A
for
loop in C-like languages consists of three parts:The loop then gets transformed into the following (roughly) equivalent loop (there are differences, but not relevant here):
So the initializer part runs first; then the loop runs as long as the condition remains true and at the end of each iteration the update part runs. It doesn't have to be an increment but the most common form looks like this:
But you can write whatever you want into those parts and you can also leave them blank if whatever you do within the loop suffices for the loop to run correctly and terminate. So in your case, since
i--
is an expression that also updatesi
, the loop just combines both condition and update into one and counts down.它将
i
初始化为this.length
,并使用条件检查来减少它。当它达到零(这是一个假值)时,循环就会停止。但请注意,因为您在检查中递减,所以循环从
this.length - 1
开始,到0
结束。所以它相当于:但是请不要使用这种语法,因为它的行为令人困惑 - 正如您可能已经注意到的那样。
It initializes
i
tothis.length
, and uses the condition check to also decrement it. When it gets to zero, which is a falsy value, the loop stops.But note that because you decrement in the check, the loop starts at
this.length - 1
and ends at0
. So it's equivalent to:But please refrain from using this kind of syntax, as its behavior is confusing - as you might have noticed.
在某个时刻,
i
将达到0
(这是一个假值),从而结束循环。更具体地说,经过几次迭代后:
i
并得到1
i
将递减并变为0
i == 0
运行i
并得到0
i
将递减并变为 < code>-1At some point,
i
will reach0
, which is a false value, and this ends the loop.More specifically, after several iterations:
i
and get1
i
will be decremented and become0
i == 0
i
and get0
i
will be decremented and become-1