简体   繁体   English

我如何理解这个for循环?

[英]How do I make sense of this for loop?

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

I thought a for loop can only be like this: 我认为for循环只能是这样的:

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

So what does that mean? 那是什么意思呢?

A for loop looks like: for循环如下所示:

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. 有问题的循环遍历数组或对象parts元素,并删除这些元素。

Basically you can rewrite a for loop like this: 基本上,您可以像这样重写for循环:

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
}

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. 您甚至可以执行for(;;) { } ,这称为永远循环。

You can also do a purely conditional for loop. 您也可以执行纯条件for循环。

for (prop in object) is the most common form of that. for (prop in object)是最常见的形式。

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;
  ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM