gpt4 book ai didi

javascript - 循环中的变量不正确

转载 作者:行者123 更新时间:2023-11-28 20:20:26 25 4
gpt4 key购买 nike

控制台未显示正确的“人员”。

我的功能如下:

(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);
}
})();

关于javascript - 循环中的变量不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18456402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com