循环变量不正确

时间:2013-08-27 03:22:17

标签: javascript

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

我的功能如下:

(function() {
  var people, length = 10;
  for (people = 0; people < this.length; people++) {
    setTimeout(function() {
      console.log(people);
    }, 1000);
  }
})();

2 个答案:

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