Home  >  Article  >  Web Front-end  >  js closures and loops

js closures and loops

巴扎黑
巴扎黑Original
2016-12-06 09:53:41876browse

function box(){
  var arr = [];
  for(var i=0;i<5;i++){
    arr[i]=function(){
      return i;
    }
  }
  return arr;
}
var b = box();
console.log(b.length);
for(var i=0;i<b.length;i++){
  console.log(b[i]())
}

The above code will print out 5 5

Because b[i]() calls an anonymous function, but the anonymous function does not execute itself, so by the time it is called, box() has already been executed. . . .

Change the following:

function box(){
  var arr = [];
  for(var i=0;i<5;i++){
    arr[i]=(
      function(num){
        console.log("ccc="+num)
        return num;
      }
    )(i)
  }
  return arr;
}
var b = box();
console.log(b.length);
for(var i=0;i<b.length;i++){
  console.log(b[i])
}

Execution result:

num=0
num=1
num=2
num=3
num=4
5
0
1
2
3
4

After modification, the anonymous function is allowed to execute itself, resulting in the final b[i] returning an array instead of a function

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn