繁体   English   中英

难题:clousure中的值已更改

[英]puzzle: value in clousure is changed

我使用http://tile.cloudmade.com/wml/latest/web-maps-lite.js进行地理编码。

有一个包含约20个地址的地址数组

addresses[n] = {where:where,who:who,contact:contact,note:note,type:type};

然后我将数组循环到地址解析

for (var i = 0; i < addresses.length; i++) {
    geocoder2.getLocations(addresses[i].where, function(response) { //a callback
       return function(k){
       Lat[k] = response.features[0].centroid.coordinates[0];
       Lng[k] = response.features[0].centroid.coordinates[1];
       latlng = new google.maps.LatLng(Lat[k], Lng[k]);
        MarkerArray[k] = new google.maps.Marker({
          map: map,
          position: latlng,
          zIndex: k,
          title: addresses[k].who,
          icon: icons(addresses[k].type.trim())
        });}(i) // a closure function called
    });
}

但是它总是对最终索引起作用。 为什么??

您有闭合回路问题。 您似乎正在尝试通过添加return function(k)...闭包来修复此问题,但这全都发生在回调函数中,因此它不会执行,直到循环退出并且i指向其最终值为止。

您必须将那个包装器推出一个级别,以便它直接在循环内:

for (var i = 0; i < addresses.length; i++) {
    geocoder2.getLocations(addresses[i].where, function(k) { //a callback
        return function(response){
            Lat[k] = response.features[0].centroid.coordinates[0];
            Lng[k] = response.features[0].centroid.coordinates[1];
            latlng = new google.maps.LatLng(Lat[k], Lng[k]);
            MarkerArray[k] = new google.maps.Marker({
                map: map,
                position: latlng,
                zIndex: k,
                title: addresses[k].who,
                icon: icons(addresses[k].type.trim())
            });
        }
    }(i)); // binding *here* instead!
}

或使用Function#bind避免嵌套函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM