Javascript 无法读取未定义的属性“forEach”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38908243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:01:23  来源:igfitidea点击:

Cannot read property 'forEach' of undefined

javascript

提问by sof

var funcs = []
[1, 2].forEach( (i) => funcs.push( () => i  ) )

Why does it produce the error below?

为什么会产生下面的错误?

TypeError: Cannot read property 'forEach' of undefined
    at Object.<anonymous>

However, the error goes away if the semicolon ;is added to the end of the first line.

但是,如果将分号;添加到第一行的末尾,错误就会消失。

回答by rvighne

There is no semicolon at the end of the first line. So the two lines run together, and it is interpreted as setting the value of funcsto

第一行末尾没有分号。所以这两行一起运行,它被解释为将值设置funcs

[][1, 2].forEach( (i) => funcs.push( () => i  ) )

The expression 1, 2becomes just 2(comma operator), so you're trying to access index 2 of an empty array:

表达式1, 2变为2逗号运算符),因此您尝试访问空数组的索引 2:

[][2] // undefined

And undefinedhas no forEachmethod. To fix this, always make sure you put a semicolon at the end of your lines (or if you don't, make sure you know what you're doing).

并且undefined没有forEach办法。要解决此问题,请始终确保在行尾添加分号(如果没有,请确保您知道自己在做什么)。

回答by maxwell

Keep the semi-colon so the variable declaration of funcs does not include the anonymous array you instantiate as belonging to the variable and also, if you are simply trying to push all the elements of the array into 'funcs' then it should look like:

保留分号,以便 funcs 的变量声明不包括您实例化为属于该变量的匿名数组,而且,如果您只是试图将数组的所有元素推送到 'funcs' 中,那么它应该如下所示:

[1, 2].forEach( (i) => funcs.push(i) )