访问嵌套对象时无法读取未定义的属性“几何”

时间:2020-11-04 23:58:13

标签: javascript arrays json

我的json输出:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [
          -118.494537,
          34.016693
        ]
      },
      "properties": []
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [
          -118.495293,
          34.011093
        ]
      },
      "properties": []
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [
          -118.494492,
          34.00922
        ]
      },
      "properties": []
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [
          -118.493904,
          34.012825
        ]
      },
      "properties": []
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [
          -118.496185,
          34.014011
        ]
      },
      "properties": []
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [
          -118.494621,
          34.015892
        ]
      },
      "properties": []
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [
          -118.47168,
          33.985714
        ]
      },
      "properties": []
    }
  ]
}

我的for循环,尝试读取“几何”时显示错误:

var saved_markers2 = [];
//looping through array of lat & long 
for (var x in saved_markers.type){ 
 saved_markers2.push(saved_markers.features[x].geometry.coordinates);
 console.log(saved_markers2);
 }

我正在按原样接收坐标的输出数组,但是我收到“几何图形”错误,导致我的网页无法加载。

当我检查以确保有一个数组正在输出时,我测试了以下代码,而没有几何错误。所以我不确定为什么必须使用for循环时收到错误消息:

 const geo0 = saved_markers.features[0].geometry.coordinates;
 const geo1 = saved_markers.features[1].geometry.coordinates;
 console.log(geo0, geo1);

  var saved_markers = [geo0, geo1];
  

0 个答案:

没有答案