This question already has answers here:
JavaScript closure inside loops – simple practical example
                            
                                (44个答案)
                            
                    
                4年前关闭。
        

    

我正在尝试在Google地图中创建交互式标记。这是创建标记的数组:

var markers = [
    {"id":17,"ti":"33 Star Hotel","lat":3.14648,"lng":101.711,"ty":5,"lid":"3","desc":""},
    {"id":9,"ti":"Aquaria KLCC","lat":3.15392,"lng":101.713,"ty":10,"lid":"3","desc":""},
    {"id":28,"ti":"Batu Ferringhi","lat":5.47436,"lng":100.247,"ty":15,"lid":"4","desc":""},
];


如果标记位置ID盖等于n,则将标记添加到地图n中。

单击标记时,我希望显示标记数组索引,但它们都显示i的最终值(markers.length)。

function map_center(n) {
    for ( var i = 0; i < markers.length; i++ ) {
        if ( markers[i].lid == n ) {
            var m = new google.maps.Marker({
                position: { lat: markers[i].lat, lng: markers[i].lng },
                map: map,
                title: markers[i].ti,
                icon: icons[markers[i].ty],
            });
            m.addListener( "click", function(){
                alert("click:" + i );
            });
            markers[i].dom = m;
        }
    }
}


不知何故,匿名函数需要一个参数来获取i的当前值的副本。我在SO上找到了此解决方案,并且可以使用,但是我不喜欢这样传递参数:

var m = new google.maps.Marker({
    position: { lat: markers[i].lat, lng: markers[i].lng },
    map: map,
    title: markers[i].ti,
    icon: icons[markers[i].ty],
    i: i
});
m.addListener( "click", function(){
    alert("click:" + this.i );
});


应该如何正确地做到这一点?

最佳答案

把所有东西都包裹起来

function map_center(n) {
for ( var i = 0; i < markers.length; i++ ) {
    (function(i) {
        if ( markers[i].lid == n ) {
            var m = new google.maps.Marker({
                position: { lat: markers[i].lat, lng: markers[i].lng },
                map: map,
                title: markers[i].ti,
                icon: icons[markers[i].ty],
            });
            m.addListener( "click", function(){
                alert("click:" + i );
            });
            markers[i].dom = m;
        }
    })(i)
}

10-08 11:45