![](/img/trans.png)
[英]Why Am I Getting “Cannot read property of undefined error” When I Can Print the Undefined Variable?
[英]why I am getting, cannot read property of undefined error?
根据快照,您使用的是chrome,Chrome很久以来就支持.forEach
。 我的猜测是,问题是由于缩小或缺少分号( ;
)
样品
function test(){ this.name = "test"; } var a = new test()['width', 'height'].forEach(key => { console.log(key); });
您已经从代码中省略了实际上导致问题的任何内容。
在[
之前,您必须具有引用对象的内容。
这意味着[]
语法成为读取属性值的语法,而不是创建数组的语法。
然后(因为使用的是逗号运算符) 'width', 'height'
解析为'height'
因此您尝试读取height
属性。
由于无论对象是什么,都没有height
属性,因此您将获得undefined
属性,该属性没有forEach
属性。
要解决此问题,请在上一条语句的末尾加上分号 。
代码的第二个版本有效,因为var
语句无法遵循您之前的语法,因此会触发自动分号插入 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.