Home > Web Front-end > JS Tutorial > js closures and loops

js closures and loops

巴扎黑
Release: 2016-12-10 09:15:16
Original
1239 people have browsed it

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]())
}
Copy after login

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])
}
Copy after login

Execution result:

Html code

num=0  
num=1  
num=2  
num=3  
num=4  
5  
0  
1  
2  
3  
4
Copy after login


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template