[英]Why does this Javascript return undefined?
var linksList = [
"http://a.com",
"http://b.com",
"http://c.com",
]
for (var i=0; i<linksList.length; i++) {
setTimeout(function() {
console.log(linksList[i]);
}, 3000);
}
I'm pasting this into Chrome inspector and it returns a number for whatever reason (it seems to be an entirely random number?)... then it waits... and then returns 3 'undefined' console errors.我将其粘贴到 Chrome 检查器中,无论出于何种原因,它都会返回一个数字(它似乎是一个完全随机的数字?)……然后它等待……然后返回 3 个“未定义”控制台错误。
Use closure:使用闭包:
for (var i=0; i<linksList.length; i++) {
(function(i){
setTimeout(function() {
console.log(linksList[i]);
}, 3000);
})(i);
}
Your problem is ,when setTimeout
's callback is called, i = linksList.length
already , so you are outputting:你的问题是,当
setTimeout
的回调被调用时, i = linksList.length
already ,所以你正在输出:
console.log(linksList[ linksList.length ]);
3
times, where linksList[ linksList.length ]
is undefined
. 3
次,其中linksList[ linksList.length ]
是undefined
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.