Error calling forEach on an array literal in javascript

前端 未结 1 923
时光取名叫无心
时光取名叫无心 2021-01-13 20:14

This code generates an error when I run it with node v6.9.2

var req = {}

[\'foo\', \'bar\'].forEach(prop => {
    console.log(\"prop: \" + prop)
});
         


        
1条回答
  •  悲哀的现实
    2021-01-13 20:32

    Automatic semicolon insertion has turned

    var req = {}
    ['foo', 'bar']
    

    into

    var req = {}['foo', 'bar']
    

    and of course {} doesn't contain a 'bar' property (because 'foo', 'bar' evaluates to 'bar').

    (undefined).forEach(...) gets evaluated, which then leads to the error that you're seeing.


    If you're relying on ASI, it's common practice to prefix lines beginning with [] or () with a semicolon:

    var req = {}
    ;['foo', 'bar']
    

    0 讨论(0)
提交回复
热议问题