gpt4 book ai didi

javascript - 如何在回调函数中向正确的对象添加值?

转载 作者:行者123 更新时间:2023-11-28 01:46:24 27 4
gpt4 key购买 nike

每次 while 循环运行时,下面的代码都会覆盖 var 存储。因此,当回调运行时,存储值通常是存储数组中的最后一项。

var stores = [];
stores.push({'address': "1 California Ave, San Francisco, CA"});
stores.push({'address': "16 California Ave, San Francisco, CA"});
stores.push({'address': "20 California Ave, San Francisco, CA"});
stores.push({'address': "30 California Ave, San Francisco, CA"});

var geocoder = new google.maps.Geocoder();

var i = 0;
while( i < stores.length){
var store = stores[i];
geocoder.geocode({'address':store.fullAddress}, function(data, status){
store.latlng = data[0].geometry.location;
}
});
i++;
};

如何将正确的纬度添加到正确的商店?

这也不起作用,因为 var i 也发生了变化。

var i = 0;
var storesObject = {}
while( i < stores.length){
var store = stores[i];
storesObject[i] = stores[i];
geocoder.geocode({'address':store.fullAddress}, function(data, status){
storesObject[i].latlng = data[0].geometry.location;
}
});
i++;
};

如果我这样做,如何将结果与商店数组匹配?

var i = 0;
var results = [];
while( i < stores.length){
var store = stores[i];
geocoder.geocode({'address':store.fullAddress}, function(data, status){
results.push(data[0].geometry.location);
}
});
i++;
};

更新添加功能范围解决了我的问题:

var i = 0;
while( i < stores.length){
(function(){
var store = stores[i];
geocoder.geocode({'address':store.fullAddress}, function(data, status){
store.latlng = data[0].geometry.location;
}
});
})();
i++;
};

参见: GMaps JS Geocode: Using/Passing Variables With Asynchronous Geocode Function?

最佳答案

function geocodeAddress(store) {
geocoder.geocode({'address':stores[store].address}, function(data, status){
if (status == google.maps.GeocoderStatus.OK) {
stores[store].latlng = data[0].geometry.location;
} else {
alert("Geocode failed: " + status);
}
});
}
var stores = [];
stores.push({'address': "1 California Ave, San Francisco, CA"});
stores.push({'address': "16 California Ave, San Francisco, CA"});
stores.push({'address': "20 California Ave, San Francisco, CA"});
stores.push({'address': "30 California Ave, San Francisco, CA"});

var geocoder = new google.maps.Geocoder();

var i = 0;
while( i < stores.length){
geocodeAddress(i);
i++;
};

关于javascript - 如何在回调函数中向正确的对象添加值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20250127/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com