Javascript - for loop index value

First, the loop index

Normal for loop var to declare variables, the results are always variable print array subscript index of the last one, how to obtain an index for each one of an array?

1, save the current value

In each cycle, it will save the current array index value to index an object inside, so that one can get an array subscript of each indexed by the object

for(var i=0;i<data.length;i++) {
  // 
  this.index = i
  alert(this.index)
}

This is the time to save each cycle index to the window object index property

2, closure

Using the internal closure function may be called characteristic variables and parameters of external functions can use the parameters passed to function inside, ensuring that every time the current index by indexing each cycle as

for(var i=0;i<data.length;i++) {
  ;(function (index) {
    alert(index)
  })(i);
}

It must be performed once per cycle function, that passed in the current index i is inevitable, can not directly execute the function cycle over again

3, ES6 grammar -let

Variables declared only let the current function is useful, can only be an internal function of the current declaration of use, and the variable var declaration, equivalent to a global variable, so the place will eventually point to the value of the var variable, constantly updated replacement

for(let i=0;i<data.length;i++) {
  alert(i)
}

Each cycle will declare a new variable i, i is a new value

Guess you like

Origin www.cnblogs.com/zjh-study/p/10958484.html