开发者

How do I make sense of this for loop?

开发者 https://www.devze.com 2023-02-21 20:13 出处:网络
for (var part; parts.length && (part = parts.shift());) {} I thought a for loop can only be like this:
for (var part; parts.length && (part = parts.shift());) {}

I thought a for loop can only be like this:

开发者_如何学Cfor (var part = 0; i < that.length; part++) {}

So what does that mean?


A for loop looks like:

for (<declarations>; <!break_condition>; <after_each_iteration>)

It's most commonplace to see a counter initialisation in the first statement, a less-than or greater-than conditional in the negated break condition, and a counter increment in the final statement.

However, the contents of each of the three parts, as long as they're syntactically valid, can be anything.

The loop in question iterates through the elements of an array or object parts, deleting those elements as it goes.


Reading this will probably explain a lot.

for (initial-expression; condition; final-expression) {
    // Block of code.
}

The initial expression is run once, before the loop starts.

The condition is checked for truth, and if true, the the final expression is run.

The final expression is run (along with the block of code) repeatedly until the condition is false.

You can put anything in any of these positions.

You can even do for(;;) { } which is known as the forever loop.

You can also do a purely conditional for loop.

for (prop in object) is the most common form of that.


Basically you can rewrite a for loop like this:

Example with common for loop usage:

for( var part = 0; i < that.length; part++) {}

rewrite as:

var part = 0;
while (i < that.length) {
// user code
part++;
}

In that other case it's the same:

for (var part; parts.length && (part = parts.shift());) {}

rewrite as:

var part;
while (parts.length && (part = parts.shift())) {
// user code
// no post code
}


So what does that mean?

It means someone isn't writing good code.

It should have been something like....

while (parts.length > 0) 
{
  var parts = parts.shift();
  if (parts == null)
    break;
  ...
0

精彩评论

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

关注公众号