Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I apologize if this a stupid question, but I cannot find the answer anywhere.

How does the following code work? (I realize that it loops over the elements of els)

var i = els.length;
while (i --> 0) {
    var el = els[i];
    // ...do stuff...
}

I have no idea what --> means. There is no documentation for it. Can someone enlighten me?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
219 views
Welcome To Ask or Share your Answers For Others

1 Answer

It should be read as

i-- > 0

So, what really happens is,

  1. value of i will be checked if it greater than 0, if it is true then control will enter the while block, if it is false while block will be skipped.

  2. Either way, the value of i will be decremented, immediately after the condition is checked.

Its always better to use for loop, when we run a loop with a counter, like this

for (var i = els.length - 1; i >= 0; i -= 1) {
    ...
}

Please read more about whether ++, -- is okay or not.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...