谁能解释一下,为什么 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
最佳答案
正如其他人所说,您缺少分号。但是……
Can anyone explain?
没有 semicolons automatically inserted在你的行之间分隔“两个”语句,因为它作为单个语句有效。它被解析(和评估)为
let a = undefined, b = undefined, c = undefined;
[a, b] = (['A', 'B']
[(b, c)] = ['BB', 'C']);
console.log(`a=${a} b=${b} c=${c}`);
其中
[a, b] = …;
是预期的解构赋值(… = ['BB', 'C'])
是一个赋值表达式,将数组赋值到左侧,并对数组求值['A', 'B'][…]
是 property reference在数组文字上(b, c)
正在使用 comma operator ,评估为c
(未定义
)
如果您想省略分号并让它们自动插入可能需要的地方,您将need to put one at the start以 (
, [
, /
, +
, -
开头的每一行或 `
。
关于javascript - ES6 数组解构怪异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38050219/