开发者

how does this syntax works?

开发者 https://www.devze.com 2023-04-11 12:13 出处:网络
erase: function(item){ for (var i = this.length; i--;) { if (this[i] === item) this.splice(i, 1); } return this;
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? Wha开发者_如何学JAVAt is it in this case?

from here.


A for loop in C-like languages consists of three parts:

for (initializer ; condition ; update) { ... }

The loop then gets transformed into the following (roughly) equivalent loop (there are differences, but not relevant here):

initializer;
while (condition) {
    ...
    update;
}

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:

for (var i = 0; i < something; i++) { ... }

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 updates i, the loop just combines both condition and update into one and counts down.


It initializes i to this.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 at 0. So it's equivalent to:

(var i = this.length - 1; i >= 0; i--)

But please refrain from using this kind of syntax, as its behavior is confusing - as you might have noticed.


At some point, i will reach 0, which is a false value, and this ends the loop.

More specifically, after several iterations:

  • It will check i and get 1
  • i will be decremented and become 0
  • The loop will run with i == 0
  • It will check i and get 0
  • i will be decremented and become -1
  • The loop will end
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号