无法使用javascript从数组中获取值

时间:2012-08-12 20:32:45

标签: javascript

我试图从回调数组中获取纬度和经度。数组有时内部有一个对象,有时还有两个对象。

  

Object {place = {...},reference = {...}}或[Object {place = {...},reference = {...}},Object {place = {... },reference = {...}}]

    Placemaker.getPlaces(text,function(o){
    console.log(o);
    if (typeof o.match!=='undefined' || o.length==1){
     latitude=o.match.place.centroid.latitude, longitude=o.match.place.centroid.longitude; 
     console.log(latitude,longitude);}
     /*else if(o=='null'){
         latitude='', longitude=''; 
     }*/
     else if (typeof o.match[0]!=='undefined' || o.match.length==2){
        latitude=o.match[0].place.centroid.latitude, longitude=o.match[0].place.centroid.longitude; 
     console.log(latitude,longitude);
     }

基本上我可以从具有一个对象的数组中获取纬度和经度,而不是从内部有两组对象时得到。这是我得到的错误

TypeError: o.match is undefined
[Break On This Error]   

else if (typeof o.match[0]!=='undefined' || o.match.length==2){

谢谢大家的帮助!

1 个答案:

答案 0 :(得分:0)

我认为你在截图中显示的是这个javascript数据结构:

var match = [
    {
        place: {
            centroid: {latitude: xx, longitude: yy},
            name: "London, England",
            type: "Town",
            woeld: "44418"
        }
        reference: {...}
    },
    {
        place: {
            centroid: {latitude: xx, longitude: yy},
            name: "Germany",
            type: "Country",
            woeld: "23424829"
        }
        reference: {...}
    }
];

您可以访问数组中每个元素的纬度和经度,如下所示:

for (var i = 0; i < match.length; i++) {
    var centroid = match[i].place.centroid;
    // latitude is centroid.latitude
    // longitude is centroid.longitude
}
相关问题