类型错误:无法读取未定义 Javascript 的属性“forEach" [英] TypeError: Cannot read property 'forEach' of undefined Javascript
本文介绍了类型错误:无法读取未定义 Javascript 的属性“forEach"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是我得到的代码无法读取未定义的属性forEach"
.
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)?
这篇关于类型错误:无法读取未定义 Javascript 的属性“forEach"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文