2016-09-20 79 views
-2

Whilest閱讀文檔:MDN Array forEach我試圖讓foreach循環裏面的索引,但只是沒有得到它..獲取JavaScript foreach循環內指數

var BANG = {}; 
 

 
BANG.boom = function (arr) { 
 
    this.array = arr; 
 
    
 
    this.start = function() { 
 
     Array.prototype.forEach.call(
 
      this.array, 
 
      (function (blubb, index) { 
 
       window.setInterval(
 
        this.hello(blubb, index), 
 
        1500 
 
       ); 
 
      }).bind(this) 
 
     ); 
 
    }; 
 

 
    this.hello = function(blubb, index) { 
 
     alert(blubb, index) 
 
    }; 
 
}; 
 

 
xxx = new BANG.boom(['xxx', 'yyy', 'zzz']); 
 
xxx.start();

我是什麼做錯了?

+0

「我在做什麼了?」 - 不使用for循環 –

+1

你是什麼意思「只是沒有得到它」? – zero298

+0

是的,你** **獲得索引:https://jsfiddle.net/9egp6qab/你只是沒有正確使用它; [Mateusz的答案](http://stackoverflow.com/a/39595489/157247)演示如何正確使用它。 –

回答

2

它的工作原理,但alert只有一個參數,所以你沒有看到它。 :)

var BANG = {}; 
 

 
BANG.boom = function (arr) { 
 
    this.array = arr; 
 
    
 
    this.start = function() { 
 
     Array.prototype.forEach.call(
 
      this.array, 
 
      (function (blubb, index) { 
 
       window.setInterval(
 
        this.hello(blubb, index), 
 
        1500 
 
       ); 
 
      }).bind(this) 
 
     ); 
 
    }; 
 

 
    this.hello = function(blubb, index) { 
 
     alert(index+":"+blubb); // only one argument 
 
     console.log(index,blubb); // console does understand the comma 
 
    }; 
 
}; 
 

 
xxx = new BANG.boom(['xxx', 'yyy', 'zzz']); 
 
xxx.start();