es6阵列解构怪异

时间:2016-06-27 09:23:17

标签: javascript ecmascript-6

任何人都可以解释一下,为什么ES6阵列解构会发生以下情况?

let a, b, c
[a, b] = ['A', 'B']
[b, c] = ['BB', 'C']
console.log(`a=${a} b=${b} c=${c}`)

// expected: a=A b=BB c=C
// actual:   a=BB b=C c=undefined

http://codepen.io/ronkot/pen/WxRqXg?editors=0011

4 个答案:

答案 0 :(得分:8)

正如其他人所说,你丢失了分号。但...

  

任何人都可以解释一下吗?

您的行之间没有semicolons automatically inserted来分隔“两个”语句,因为它作为单个语句有效。它被解析(并评估)为

<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Modal Header</h4>
      </div>
      <div class="modal-body">
        <p>Some text in the modal.</p>
        <iframe src="testing1.php" width="200" height="200"></iframe>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>

  </div>
</div>

,其中

  • let a = undefined, b = undefind, c = undefined; [a, b] = (['A', 'B'] [(b, c)] = ['BB', 'C']); console.log(`a=${a} b=${b} c=${c}`); 是预期的解构分配
  • [a, b] = …;是一个赋值表达式,将数组分配给左侧,并评估数组
  • (… = ['BB', 'C'])是数组文字的property reference
  • ['A', 'B'][…]正在使用comma operator,评估为(b, c)c

答案 1 :(得分:3)

您已经陷入了JavaScript换行和自动分号插入规则的陷阱。

举个例子:

let x = [1, 2]
[2, 1]

它被解释为:

let x = [1, 2][2, 1] // === [1, 2][(2, 1)] === [1, 2][1] === 2

上面那个奇怪的[(2, 1)]事与Comma Operator的工作方式有关。

因此,你的例子:

let a, b, c
[a, b] = ['A', 'B']
[b, c] = ['BB', 'C']
console.log(`a=${a} b=${b} c=${c}`)

被解释为:

let a, b, c
[a, b] = ['A', 'B'][b, c] = ['BB', 'C']
console.log(`a=${a} b=${b} c=${c}`)

现在,如果您插入分号,它将按预期工作:

let a, b, c
[a, b] = ['A', 'B']; // note a semicolon here
[b, c] = ['BB', 'C']
console.log(`a=${a} b=${b} c=${c}`)

此外,最好通过将代码粘贴到Babel repl来查看生成的输出来检查代码:

'use strict';

var a = void 0,
    b = void 0,
    c = void 0;

var _ref = ['A', 'B'][(b, c)] = ['BB', 'C'];

a = _ref[0];
b = _ref[1];

console.log('a=' + a + ' b=' + b + ' c=' + c);

答案 2 :(得分:2)

我相信你已经忘记了换行符&#39 ;;&#39;。以下是更正后的代码。请尝试:

let a,b,c
[a, b] = ['A', 'B'];
[b, c] = ['BB', 'C'];
console.log(`a=${a} b=${b} c=${c}`)

答案 3 :(得分:-1)

let a, b, c
[a, b] = ['A', 'B']***;***
[b, c] = ['BB', 'C']
console.log(`a=${a} b=${b} c=${c}`)
  

控制台:a = A b = BB c = C