Javascript 循环中的变量不正确

Javascript 循环中的变量不正确,javascript,Javascript,控制台未显示正确的“人员” 我的职能如下: (function() { var people, length = 10; for (people = 0; people < this.length; people++) { setTimeout(function() { console.log(people); }, 1000); } })(); (函数(){ 变量人,长度=10; for(people=0;people

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

我的职能如下:

(function() {
  var people, length = 10;
  for (people = 0; people < this.length; people++) {
    setTimeout(function() {
      console.log(people);
    }, 1000);
  }
})();
(函数(){
变量人,长度=10;
for(people=0;people
在代码中
此.length
不是函数中的局部变量
length

只是全局对象
窗口
,因此
此.length
只是
窗口.length

(function() {
    var people,length = 10;
    for (people = 0; people < length; people++) {        
        setTimeout((function(people){ 
           return function() { 
              console.log(people); 
           };
        })(people), 1000);
    }
})();
(函数(){
变量人,长度=10;
for(people=0;people
在代码中
此.length
不是函数中的局部变量
length

只是全局对象
窗口
,因此
此.length
只是
窗口.length

(function() {
    var people,length = 10;
    for (people = 0; people < length; people++) {        
        setTimeout((function(people){ 
           return function() { 
              console.log(people); 
           };
        })(people), 1000);
    }
})();
(函数(){
变量人,长度=10;
for(people=0;people
你的意思是:

(function() {
    var people,length = 10;
    for (people = 0; people < length; people++) {
        (function(index) {
            setTimeout(function() { console.log(index); }, 1000);
        })(people);
    }
})();
(函数(){
变量人,长度=10;
for(人=0;人<长度;人++){
(功能(索引){
setTimeout(函数(){console.log(index);},1000);
})(人);
}
})();
你的意思是:

(function() {
    var people,length = 10;
    for (people = 0; people < length; people++) {
        (function(index) {
            setTimeout(function() { console.log(index); }, 1000);
        })(people);
    }
})();
(函数(){
变量人,长度=10;
for(人=0;人<长度;人++){
(功能(索引){
setTimeout(函数(){console.log(index);},1000);
})(人);
}
})();

它显示了什么?您希望得到什么结果?不是
这个.length
应该是
length
而是
设置超时(“console.log(“+people+”),1000)你想要什么?或者希望它每秒输出一个数字?希望控制台中显示1到10。看不到它显示除10以外的任何内容。谢谢@raser,接得好。试试我当时写的。如果你想从1到10,for循环需要是:
for(people=1;people它显示了什么?你期望得到什么结果?而不是
this.length
它不应该是
length
这是
setTimeout(“console.log(“+people+”),1000);
你想要什么?或者你想让它每秒输出一个数字?希望在控制台中显示1到10。看不到它只显示10。谢谢@raser很好的提示。试试我写的。如果你想从1到10,for循环需要是:
for(people=1;people+1这是一种更好的设置超时的方法(
setTimeout(“console.log(+people+”),1000);
+1并将在7分钟内接受!:)谢谢@Sudhir-1的解释。Poster不会知道它为什么会坏。+1这是一种更好的设置超时的方法(
setTimeout(“console.log(+people+”),1000);
+1并将在7分钟内接受!:)谢谢@Sudhir-1没有解释。海报不会知道它为什么会坏。谢谢@xdazz的解释!+1谢谢@xdazz的解释!+1