Cannot read property 'forEach' of undefine

2020-02-06 05:23发布

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.

标签: javascript
2条回答
2楼-- · 2020-02-06 06:06

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

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).

查看更多
叛逆
3楼-- · 2020-02-06 06:12

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:

[1, 2].forEach( (i) => funcs.push(i) )
查看更多
登录 后发表回答