Interesting behavior about ES6 array destructuring and swapping

前端 未结 2 1941
忘了有多久
忘了有多久 2020-12-11 14:23

I just noticed that the following code, without immediately referencing one after let [one, two] = [1, 2], trying [one, two] = [two, one]

相关标签:
2条回答
  • 2020-12-11 14:45

    Add a semicolon to the 1st line, because the interpreter assumes that lines 1 and 2 declarations happen together, and one (and two) is not defined yet:

    let [one, two, three] = [1, 2, 3];
    [one, two] = [two, one]
    console.log(one, two)

    0 讨论(0)
  • 2020-12-11 14:52

    Cause its parsed like this:

     let [one, two, three] = [1, 2, 3][one, two] = [one, two]
    

    To make it work, always suround destructuring assignments with parens:

     let [one, two, three] = [1, 2, 3];
     ([one, two] = [two, one]);
     console.log(one, two);
    

    And never ever trust ASI, there are some cases like this were it goes wrong.

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