无法读取未定义的属性"forEach" [英] Cannot read property 'forEach' of undefined
本文介绍了无法读取未定义的属性"forEach"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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.
推荐答案
第一行末没有分号.因此这两行同时运行,这被解释为将 funcs
的值设置为
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 funcs
to
[][1, 2].forEach( (i) => funcs.push( () => i ) )
The expression 1, 2
becomes just 2
(comma operator), so you're trying to access index 2 of an empty array:
[][2] // undefined
并且 undefined
没有 forEach
方法.要解决此问题,请始终确保在行末添加分号(否则,请确保您知道自己在做什么).
And undefined
has no forEach
method. 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).
这篇关于无法读取未定义的属性"forEach"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文