[Javascript] Advanced Function Scope

Something like 'for' or 'while', 'if', they don't create a new scope:

var ary = [,,];

for(var i = ; i < ary.length; i++){
var greeting = "Hello";
var times = i;
} console.log(i); //
console.log(times); //
console.log(greeting); // Hello

Everyting written in for loop can be accessed outside the for loop.

So, the problem:

var ary = [,,];

for(var i = ; i < ary.length; i++){
setTimeout( function(i){
console.log(ary[i]); //undefined, becaues i = 3 always
}, )
}

Solve the problem:

var ary = [,,];

for(var i = ; i < ary.length; i++){
// Function do create scope
(function(){
// Remember i in j
var j = i;
setTimeout( function(){
// So now each j is different
console.log(ary[j]);
}, )
})();
}
上一篇:JavaScript中URL的解码和编码


下一篇:javascript中escape()、unescape()、encodeURI()、encodeURIComponent()、decodeURI()、decodeURIComponent()比较