[英]JavaScript push Array into Array
我目前正在使用Google地圖的地理編碼,需要創建一個包含數組作為元素的數組。
基本上我需要創建這個:
var locations = [
['Bondi Beach', -33.890542, 151.274856, 4],
['Coogee Beach', -33.923036, 151.259052, 5],
['Cronulla Beach', -34.028249, 151.157507, 3],
['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
['Maroubra Beach', -33.950198, 151.259302, 1]
];
但動態! 我需要這個數組以后將引腳放在地圖上。
我在做什么:
var locations = []; // The initial array
for (var i = 0; i < addresses.length; ++i){
var address=addresses[i]; // the address e.g. 15 Main St, Hyannis, MA
geocoder.geocode({ 'address': address}, function(results){
var obj = {
0: address,
1: results[0].geometry.location.hb,
2: results[0].geometry.location.ib,
3: i
};
console.log(obj);
locations.push(new Array());
locations[i].push(obj);
});
};
console.log(locations.length);
問題,問題:
我沒有看到任何錯誤,但在最后位置[]數組是空的。
如果需要,這是一個控制台屏幕:
這應該是你所需要的:
geocoder.geocode({ 'address': address}, function(results){
locations.push([
address,
results[0].geometry.location.hb,
results[0].geometry.location.ib,
i //this is actually going to always be
//addresses.length because the callback won't fire
//until well after the loop has completed.
//Is this really a necessary field to have
//in your array? if so, you'll need to refactor a bit
]);
});
我沒有時間測試代碼,但它應該這樣工作:
function requestLocations( addresses, callback ) {
var remainingLocations = addresses.length;
var locations = [];
for (var i = 0; i < addresses.length; ++i){
var address=addresses[i]; // the address e.g. 15 Main St, Hyannis, MA
locations[i] = [];
geocoder.geocode({ 'address': address}, (
function(idx) {
return function(result) {
locations[idx] = [ addresses[idx],
results[0].geometry.location.hb,
results[0].geometry.location.ib,
idx
];
//decrement the number of remaining addresses
--remainingLocations;
//if there are no more remaining addresses and a callback is provided then call this calback with the locations
if( remainingLocations === 0 && callback ) {
callback(locations);
}
}; // returns the real callback function for your geocoding
})(i) //direct invocation of function with paramter i for scoping
);
}
}
requestLocations(addresses, function( locations ) {
console.dir(locations);
console.log(locations.length);
});
代碼問題如下。 首先執行這部分代碼:
var locations = []; // The initial array
for (var i = 0; i < addresses.length; ++i) {
var address = addresses[i]; // the address e.g. 15 Main St, Hyannis, MA
geocoder.geocode({
'address': address
}, function(results) {
//this part is called later when that data is ready (it is an asynchronous callback)
});
};
//because of the async request this is still 0
console.log(locations.length);
之后,只要瀏覽器從服務器接收數據,就會調用回調本身:
function(results) {
var obj = {
0: address,
1: results[0].geometry.location.hb,
2: results[0].geometry.location.ib,
3: i
};
console.log(obj);
locations.push(new Array());
locations[i].push(obj);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.