Home > Web Front-end > JS Tutorial > body text

js closures and loops

巴扎黑
Release: 2016-12-06 09:53:41
Original
875 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:

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

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

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