控制台未显示正确的“人”。
我的功能如下:
(function() {
var people, length = 10;
for (people = 0; people < this.length; people++) {
setTimeout(function() {
console.log(people);
}, 1000);
}
})();
控制台未显示正确的“人”。
我的功能如下:
(function() {
var people, length = 10;
for (people = 0; people < this.length; people++) {
setTimeout(function() {
console.log(people);
}, 1000);
}
})();
在您的代码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);
}
})();
你的意思是:
(function() {
var people,length = 10;
for (people = 0; people < length; people++) {
(function(index) {
setTimeout(function() { console.log(index); }, 1000);
})(people);
}
})();