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

js closures and loops

巴扎黑
巴扎黑Original
2016-12-10 09:15:161167browse

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:

Html code

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


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