Object creation in loop broken; unrolled works

前端 未结 2 1045
隐瞒了意图╮
隐瞒了意图╮ 2020-12-11 13:48

I\'m doing some testing and ran into this bizarre situation: The first case (assigning objects like InfoWindows in a loop) does not work as expected, while writing the assig

相关标签:
2条回答
  • 2020-12-11 14:02
    var iwArray = [];
    for (var i = 0; i < 3; i++) {
      iwArray[i] = new google.maps.InfoWindow({content: "w " + i });
      google.maps.event.addListener(marker[i], 'mouseover', createListener(i, map));
    }
    
    function createListener(i, map) {
        return function(e) {
            iwArray[i].open(map, this);
        };
    }
    
    0 讨论(0)
  • 2020-12-11 14:10

    Use closure:

     for (var i = 0; i < 3; i++) {
        (function(i){
           iwArray[i] = new google.maps.InfoWindow({content: "w "});
           google.maps.event.addListener(marker[i], 'mouseover', function(e) {
              iwArray[i].open(map, this);
           });
        })(i);
    }
    
    0 讨论(0)
提交回复
热议问题