ES6阵列破坏性怪异

ES6阵列破坏性怪异

本文介绍了ES6阵列破坏性怪异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释一下,为什么ES6阵列解构会发生以下情况?

Can anyone explain, why the following happens with ES6 array destructuring?

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

推荐答案

正如其他人所说,您缺少分号.但是...

As others have said, you're missing semicolons. But…

您的行之间没有自动插入分号以分隔两个"语句,因为它作为单一声明.它被解析(并评估)为

There are no semicolons automatically inserted between your lines to separate the "two" statements, because it is valid as a single statement. It is parsed (and evaluated) as

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'])是一个赋值表达式,将数组分配到左侧,并求值到数组
  • ['A', 'B'][…]属性参考在数组文字上
  • (b, c)正在使用逗号运算符,计算结果为c(即undefined)
  • [a, b] = …; is a destructuring assignment as expected
  • (… = ['BB', 'C']) is an assignment expression assigning the array to the left hand side, and evaluating to the array
  • ['A', 'B'][…] is a property reference on an array literal
  • (b, c) is using the comma operator, evaluating to c (which is undefined)

如果您想省略分号并在需要的地方自动插入分号,您将需要在以([/+-`.

If you want to omit semicolons and let them be automatically inserted where ever needed, you will need to put one at the begin of every line that starts with (, [, /, +, - or `.

这篇关于ES6阵列破坏性怪异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!