TypeError:无法读取未定义Javascript的属性'forEach' [英] TypeError: Cannot read property 'forEach' of undefined Javascript

查看:95
本文介绍了TypeError:无法读取未定义Javascript的属性'forEach'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我正在获取无法读取未定义的属性'forEach'的代码.

Following is the code in which I am getting Cannot read property 'forEach' of undefined.

const print2 = function(x, y) {
  console.log(x*y)
}

[1,2,3,4].forEach( x => print2(x, 20) )

让我知道我在这里做错了,尽管我愿意-

Let me know what I am doing wrong here, though if I do -

function print2(x, y) {
  console.log(x*y)
}

[1,2,3,4].forEach( x => print2(x, 20) )

这很好.

推荐答案

由于该函数后没有分号,因此该代码段的解释如下:

Since there's no semicolon after the function, the snippet gets interpreted as the following:

const print2 = function(x, y) {
  console.log(x*y)
}[1,2,3,4].forEach( x => print2(x, 20) )

这意味着它正在尝试索引该函数.在函数之后或数组文字之前添加分号:

Which means that it's trying to index into the function. Add a semicolon either after the function, or before the array literal:

const print2 = function(x, y) {
  console.log(x*y)
};

[1,2,3,4].forEach( x => print2(x, 20) )

const print2 = function(x, y) {
  console.log(x*y)
}

;[1,2,3,4].forEach( x => print2(x, 20) )

此处提供有关Javascript自动分号插入的更多信息: JavaScript自动分号插入(ASI)的规则是什么?

More about Javascript's automatic semicolon insertion here: What are the rules for JavaScript's automatic semicolon insertion (ASI)?

这篇关于TypeError:无法读取未定义Javascript的属性'forEach'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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