为什么我越来越无法读取未定义错误的属性? [英] why I am getting, cannot read property of undefined error?

查看:48
本文介绍了为什么我越来越无法读取未定义错误的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码

function Test(){

}
new Test()



['width', 'height'].forEach(key => {
  console.log(key);
});

给我错误

但此代码不

function Test(){

}
new Test()

var arr = ['width', 'height'];
arr.forEach(key => {
  console.log(key);
});

为什么?

我正在使用Chrome版本53.0.2785.116(64位)-Macbook air 2014

I am using chrome Version 53.0.2785.116 (64-bit) - Macbook air 2014

推荐答案

您已经从代码中省略了实际上导致问题的任何原因.

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.

然后(因为您使用的是逗号运算符)'width','height'解析为'height',因此您尝试读取 height属性.

Then (because you are using a comma operator) 'width', 'height' resolves as 'height' so you are trying to read the height property.

由于无论对象是什么,都没有 height 属性,因此会得到 undefined ,它没有 forEach 属性.

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

要解决此问题,请在上一条语句的末尾添加分号.

代码的第二个版本有效,因为 var 语句不能遵循您之前的语法,因此会触发自动分号插入.

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.

这篇关于为什么我越来越无法读取未定义错误的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆