Javascript 实现forloop on click addListener

Javascript 实现forloop on click addListener,javascript,Javascript,我正在将GoogleMap实现到ionic,但我在尝试实现marker和infowindow时遇到了一个问题 正如您在下面看到的,一旦我尝试对每个标记实现infowindow,它就会按预期工作: this.markerStart[0].addListener('click',()=>{ console.log('clicked') this.popuparray[0].open(this.map,this.markerStart[0]);

我正在将GoogleMap实现到ionic,但我在尝试实现marker和infowindow时遇到了一个问题

正如您在下面看到的,一旦我尝试对每个标记实现infowindow,它就会按预期工作:

this.markerStart[0].addListener('click',()=>{
             console.log('clicked')
             this.popuparray[0].open(this.map,this.markerStart[0]);
         })
         this.markerStart[1].addListener('click',()=>{
             console.log('clicked2222')
             this.popuparray[1].open(this.map,this.markerStart[1]);
         })
但当我试图修改它以使用for循环时,它就不起作用了

它看起来一模一样,但我不知道为什么不起作用

//在这里,this.markerStart.length是2…但它在for循环中不起作用

console.log(this.markerStart);
    console.log(this.markerStart.length);
    console.log("this.markerStart")
    for(var j=0; j<this.markerStart.length; j++){
        this.markerStart[j].addListener('click',()=>{
            console.log(j);
            //only log 2 ...which is I don't understand. why log 2?
           // j should be 0 and 1...because this.markerStart.length is 2
            this.popuparray[j].open(this.map,this.markerStart[j])

        })
    }
我也试过这个:

  for(var j=0; j<2; j++){

        this.markerStart[j].addListener('click',()=>{
            console.log(j);
        })
    }
起初我认为,当我单击第一个标记时,它应该记录为1,当单击第二个标记时,它应该记录为2,但它只记录为2。

上一个解决方案有效,所以为什么没有得到预期的结果呢。您可以使用let而不是var,它将起作用。var将保留您的变量,并且对于每个迭代,您将只更改唯一的变量j。毕竟,你提到了一个变量j,它的值是2。对于每次迭代,将使用let创建一个新变量,每个函数将有自己的变量j

只需替换var j=0;设j=0;在for循环中,它将按照您的预期工作

因为let声明的变量的作用域仅限于它所使用的块、语句或表达式。另一方面,var全局定义变量,或局部定义整个函数的变量,而不考虑块范围。

调用click时,j是this.markerStart.length-哪个是2?
 for(let j = 0; j < 2; j++){
     this.markerStart[j].addListener('click',() => console.log(j));
 }
for(var j = 0; j < 2; j++){
    ((k) => this.markerStart[k].addListener('click', () => console.log(k)))(j);
}