JavaScript,无法读取未定义的属性,但已定义

时间:2019-10-03 20:40:08

标签: javascript

我不知道为什么在console.log上可以看到的undefined上找到这个变量。没有紧急呼叫。

if (gLayer) {
    /* This code works ok, but I don't want to use this way, instead, I want to use the next block code:

    var longZoom = gLayer.graphics[0].geometry.rings[0][0][0];
    var latZoom = gLayer.graphics[0].geometry.rings[0][0][1];
    zoomToLocationLatLon(latZoom, longZoom, false, 12);

    */


    console.log('gLayer', gLayer); // I can see in the console the var gLayer
    console.log('gLayer.graphics', gLayer.graphics); // I can see in the console the var gLayer.graphics, its an array of ~1200 rows
    if(gLayer.graphics && gLayer.graphics.length > 0) {
        var ge = GraphicsUtils.graphicsExtent(gLayer.graphics);  <-- HERE I HAVE AN ERROR.
        map.setExtent(ge, true);
    }
    gLayer.show();
}

错误是Uncaught TypeError: Cannot read property 'graphicsExtent' of undefined为什么说未定义?实际上,通过逐步使用Chrome的JS调试器,我可以看到将其定义为Array:

enter image description here

然后在下一步中我得到了

enter image description here

3 个答案:

答案 0 :(得分:1)

GraphicsUtils未定义。您的代码不清楚您何时定义或加载它。但是您可以检查该值是否可用:

if(gLayer.graphics && gLayer.graphics.length > 0 && GraphicsUtils) {
    var ge = GraphicsUtils.graphicsExtent(gLayer.graphics);
    map.setExtent(ge, true);
} else {
  console.warn('GraphicsUtils is not defined');
}

答案 1 :(得分:0)

读取错误:GraphicsUtils不确定,不是您所记录的内容。

答案 2 :(得分:0)

您的错误消息是:Cannot read property 'graphicsExtent' of undefined

问题是GraphicUtilsundefined而不是gLayergLayer.graphics