0

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

我的功能如下:

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

2 回答 2

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);
    }
})();
于 2013-08-27T03:25:54.680 回答
1

你的意思是:

(function() {
    var people,length = 10;
    for (people = 0; people < length; people++) {
        (function(index) {
            setTimeout(function() { console.log(index); }, 1000);
        })(people);
    }
})();
于 2013-08-27T03:26:54.070 回答