简体   繁体   English

对于循环值,每次迭代

[英]For loop values each iteration

I'm not sure if these functions do exactly the same thing: 我不确定这些功能是否完全相同:

Is: 方法是:

  for (i=0, l=this.current_columns.length; i<l; i++) {
    if ( this.current_columns[i].text === row[0] ) {
        this.current_columns.splice(i, 1);
        EV.publish('edit_layout.current_columns', {data: [this.current_columns]})
        break;
    }
  }

equal to: 等于:

  for (i=0; i<this.current_columns.length; i++) {
    if ( this.current_columns[i].text === row[0] ) {
        this.current_columns.splice(i, 1);
        EV.publish('edit_layout.current_columns', {data: [this.current_columns]})
        break;
    }
  }

In the end outcome? 到底结果如何?

They actually do the same thing, but it may need some explanation: 他们实际上做了同样的事情,但是可能需要一些解释:

The difference in the loop itself is that the length of the array is stored in a variable in the first version. 循环本身的区别在于,数组的长度存储在第一个版本的变量中。

Storing the length in a variable means that the loop will run to the original length of the array, if the array changes inside the loop, that would be a problem. 将长度存储在变量中意味着循环将运行到数组的原始长度,如果数组在循环内发生更改,那将是一个问题。

The array happens to change in the loop, but as you also have a break; 数组碰巧在循环中发生了变化,但是您也有break; after that, it's not a problem. 在那之后,这不是问题。 The loop ends, so it doesn't matter that the length in the variable is no longer correct. 循环结束,因此变量的长度不再正确无所谓。

This part: 这部分:

for (i=0, l=this.current_columns.length; i<l; i++) {

the first part: i=0, l=this.current_columns.length is executed once, whereas i<l is executed at each iteration. 第一部分: i=0, l=this.current_columns.length执行一次,而i<l在每次迭代时执行。

It is thus generally better to precalculate the boundary of a loop. 因此,通常最好预先计算一个循环的边界。 Be careful though, because sometimes your loop modifies the length of the array it traverses, you have then a choice: whether you calculate at each iteration the length of the array or you modify i and l in consequence (if you remove an element l = l - 1 , and i = i - 1 ) 但是要小心,因为有时您的循环会修改它遍历的数组的长度,所以您可以选择:是在每次迭代时计算数组的长度,还是修改il (如果删除元素l = l - 1 ,而i = i - 1

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

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