ES6 数组解构怪异 [英] ES6 Array destructuring weirdness

查看:36
本文介绍了ES6 数组解构怪异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

让 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//实际:a=BB b=C c=undefined

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

解决方案

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

<块引用>

谁能解释一下?

在您的行之间没有分号自动插入来分隔两个"语句,因为它作为单个语句是有效的.它被解析(和评估)为

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'][…] 是一个 属性引用 数组文字
  • (b, c) 正在使用 逗号运算符,计算结果为c(即undefined)

如果您想省略分号并让它们自动插入可能需要的地方,您将需要在以(开头的每一行的开始放一个code>、[/+-`.>

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…

Can anyone explain?

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 = undefined, c = undefined;
[a, b] = (['A', 'B']
[(b, c)] = ['BB', 'C']);
console.log(`a=${a} b=${b} c=${c}`);

wherein

  • [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 possible needed, you will need to put one at the start of every line that begins with (, [, /, +, - or `.

这篇关于ES6 数组解构怪异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆