代码之家  ›  专栏  ›  技术社区  ›  Kevin Qian

ES6阵列解构和交换的有趣行为

  •  2
  • Kevin Qian  · 技术社区  · 6 年前

    我只是注意到以下代码,没有立即引用 one 之后 let [one, two] = [1, 2] 尝试 [one, two] = [two, one] 将崩溃:

    let [one, two, three] = [1, 2, 3]
    [one, two] = [two, one] // CRASH! one is not defined
    console.log(one, two)

    但是,只需添加一个未使用的 在声明和交换之间突然允许代码,但不正确:

    let [one, two, three] = [1, 2, 3]
    one // inserted here
    [one, two] = [two, one] // no longer crashes! but not actually swapping
    console.log(one, two) // should be '2 1', but shows '1 2' instead

    而下面的代码给出了预期的交换效果

    var a = 1;
    var b = 3;
    
    [a, b] = [b, a];
    console.log(a); // 3
    console.log(b); // 1

    有人能解释为什么会有这样的行为吗?谢谢

    2 回复  |  直到 6 年前
        1
  •  6
  •   Ori Drori    6 年前

    在第1行中添加分号,因为解释器假定第1行和第2行声明同时发生,并且 one (和 two )尚未定义:

    let [one, two, three] = [1, 2, 3];
    [one, two] = [two, one]
    console.log(one, two)
        2
  •  2
  •   Rehan Haider    6 年前

    导致其解析如下:

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

    要使其正常工作,请始终使用parens围绕解构工作分配:

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

    永远不要相信ASI,如果它出了问题,也会有类似的情况。