2016-09-20 3 views
-2

内のインデックスを取得します:MDN Array forEach私はドキュメントを読んWhilest 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();

私は何をしています.. foreachループ内のインデックスを取得しようとしているが、ちょうどそれが届きません間違っている?

+0

"私が間違って何をしているのですか?" - forループを使用していない –

+1

「それを取得していない」とはどういう意味ですか? – zero298

+0

はい、あなた** **はインデックスを取得しています:https://jsfiddle.net/9egp6qab/あなたはちょうどそれを正しく使用していません。 [Mateuszの答え](http://stackoverflow.com/a/39595489/157247)は、正しく使用する方法を示しています。 –

答えて

2

これは機能しますが、alertは引数が1つしかないので、表示されません。 :)

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