控制台未显示正确的“人物”。
我的功能如下:
(function() {
var people, length = 10;
for (people = 0; people < this.length; people++) {
setTimeout(function() {
console.log(people);
}, 1000);
}
})();
答案 0 :(得分:2)
在您的代码中this.length
不是您函数中的局部变量length
。
this
只是全局对象window
,因此this.length
只是window.length
。
(function() {
var people,length = 10;
for (people = 0; people < length; people++) {
setTimeout((function(people){
return function() {
console.log(people);
};
})(people), 1000);
}
})();
答案 1 :(得分:1)
(function() {
var people,length = 10;
for (people = 0; people < length; people++) {
(function(index) {
setTimeout(function() { console.log(index); }, 1000);
})(people);
}
})();