Home > Article > Web Front-end > js closures and loops
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