简体   繁体   中英

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

As per snapshot, you are using chrome and Chrome supports .forEach from a long time. 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.

Since there is no height property on whatever the object is, you get undefined which doesn't have a forEach property.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM