Associative Javascript Array
I have an issue and this is not something that I have ever used before.
This is a snippet of the code.
//Defined at top of file
var ships_array = [];
//Function later on
function refreshJSON(){
$.getJSON("scripts/getJSON.php", function(json){
if(json){
$.each(shiplist,function(i,item){
$.each(item,function(j,subitem){
var mmsi = subitem['mmsi'];
ships_array[mmsi].lat = subitem['lat'];
ships_array[mmsi].lon = subitem['lon'];
});
});
}
});
}
The error I a开发者_Python百科m getting is
ships_array[mmsi] is undefined [Break On This Error] ships_array[mmsi].lat = subitem['lat'];
Is this the right way to use an associative array? I have seen an example similar to this but I am going wrong somewhere! At the end of it I want an array of Google Maps markers!
you just need to initialize the value at the hash key first
var mmsi = subitem['mmsi'];
ships_array[mmsi] = ships_array[mmsi] || {};
ships_array[mmsi].lat = subitem['lat'];
ships_array[mmsi].lon = subitem['lon'];
You can change your code like this:
//Defined at top of file
var ships_array = [];
//Function later on
function refreshJSON(){
$.getJSON("scripts/getJSON.php", function(json){
if(json){
$.each(shiplist,function(i,item){
$.each(item,function(j,subitem){
var mmsi = subitem['mmsi'];
ships_array[mmsi] = {lat: subitem['lat'], lon:subitem['lon']};
});
});
}
});
}
精彩评论