类型错误:无法读取未定义 Javascript 的属性“forEach”

Nes*_*esh 4 javascript callback node.js ecmascript-6

以下是我得到的代码Cannot read property 'forEach' of undefined

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

[1,2,3,4].forEach( x => print2(x, 20) )
Run Code Online (Sandbox Code Playgroud)

让我知道我在这里做错了什么,但如果我这样做 -

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

[1,2,3,4].forEach( x => print2(x, 20) )
Run Code Online (Sandbox Code Playgroud)

这工作正常。

在此处输入图片说明

cub*_*brr 10

由于函数后没有分号,代码片段被解释为如下:

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

这意味着它正在尝试对函数进行索引。在函数之后或数组文字之前添加一个分号:

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

[1,2,3,4].forEach( x => print2(x, 20) )
Run Code Online (Sandbox Code Playgroud)

或者

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

;[1,2,3,4].forEach( x => print2(x, 20) )
Run Code Online (Sandbox Code Playgroud)

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


Bar*_*mar 6

在变量声明的末尾需要一个分号。

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

[1,2,3,4].forEach( x => print2(x, 20) )
Run Code Online (Sandbox Code Playgroud)

没有分号,它被视为

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

[1,2,3,4]被解释为属性访问器,而不是数组,逗号运算符返回最后一个值4。由于该函数没有4属性,因此返回undefined,然后您尝试调用.forEach()它。