var funcs = []
[1, 2].forEach( (i) => funcs.push( () => i ) )
为什么会产生下面的错误?
TypeError: Cannot read property 'forEach' of undefined
at Object.<anonymous>
但是,如果分号,错误就会消失;
添加到第一行的末尾。
第一行末尾没有分号。所以这两行是一起运行的,它被解释为设置funcs
to
[][1, 2].forEach( (i) => funcs.push( () => i ) )
表达方式1, 2
变得只是2
(逗号运算符 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator),因此您尝试访问空数组的索引 2:
[][2] // undefined
And undefined
has no forEach
方法。要解决此问题,请始终确保在行尾添加分号(或者如果没有,请确保您知道自己在做什么)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)