[英]why I am getting, cannot read property of undefined error?
This code 这段代码
function Test(){ } new Test() ['width', 'height'].forEach(key => { console.log(key); });
gives me error 给我错误
but this code not 但是这段代码不是
function Test(){ } new Test() var arr = ['width', 'height']; arr.forEach(key => { console.log(key); });
why? 为什么?
I am using chrome Version 53.0.2785.116 (64-bit) - Macbook air 2014 我正在使用Chrome版本53.0.2785.116(64位)-Macbook air 2014
As per snapshot, you are using chrome and Chrome supports .forEach
from a long time. 根据快照,您使用的是chrome,Chrome很久以来就支持
.forEach
。 My guess is, issue is due to minification or missing semicolon( ;
) 我的猜测是,问题是由于缩小或缺少分号(
;
)
Sample 样品
function test(){ this.name = "test"; } var a = new test()['width', 'height'].forEach(key => { console.log(key); });
You've omitted whatever is actually causing the problem from your code. 您已经从代码中省略了实际上导致问题的任何内容。
Immediately before the [
you must have something which refers to an object. 在
[
之前,您必须具有引用对象的内容。
This means that the []
syntax becomes the syntax to read a property value instead of the syntax to create an array. 这意味着
[]
语法成为读取属性值的语法,而不是创建数组的语法。
Then (because you are using a comma operator) 'width', 'height'
resolves as 'height'
so you are trying to read the height
property. 然后(因为使用的是逗号运算符)
'width', 'height'
解析为'height'
因此您尝试读取height
属性。
Since there is no height
property on whatever the object is, you get undefined
which doesn't have a forEach
property. 由于无论对象是什么,都没有
height
属性,因此您将获得undefined
属性,该属性没有forEach
属性。
To fix this put a semicolon at the end of the previous statement . 要解决此问题,请在上一条语句的末尾加上分号 。
The second version of your code works because the var
statement can't follow the syntax you have just before it, so it triggers automatic semicolon insertion . 代码的第二个版本有效,因为
var
语句无法遵循您之前的语法,因此会触发自动分号插入 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.