【发布时间】:2016-01-08 22:38:51
【问题描述】:
在咖啡脚本中这很简单:
coffee> a = ['a', 'b', 'program']
[ 'a', 'b', 'program' ]
coffee> [_..., b] = a
[ 'a', 'b', 'program' ]
coffee> b
'program'
es6 是否允许类似的东西?
> const [, b] = [1, 2, 3]
'use strict'
> b // it got the second element, not the last one!
2
> const [...butLast, last] = [1, 2, 3]
SyntaxError: repl: Unexpected token (1:17)
> 1 | const [...butLast, last] = [1, 2, 3]
| ^
at Parser.pp.raise (C:\Users\user\AppData\Roaming\npm\node_modules\babel\node_modules\babel-core\node_modules\babylon\lib\parser\location.js:24:13)
我当然可以用 es5 的方式来做 -
const a = b[b.length - 1]
但也许这有点容易出错。 splat 只能是解构中的最后一件事吗?
【问题讨论】:
-
@FelixKling 这个问题特别是关于
...在 es6 中的行为,特别是它只能在解构或参数列表中用作最后一件事。这对于从咖啡脚本进入 es6 的人来说可能是违反直觉的,因此这个问题可能很有用。 -
这意味着除了
[1,2,3].slice(-1),你甚至不能解构等价于[1,2,3].slice(0, -1)。这些是常见的操作。 ES6 解构在某种程度上是个笑话! -
@Iven 有正当理由 - 处理无限迭代。
-
太糟糕的休息,因为第一个参数不起作用。本来会很酷...这是一个使用一些答案的jsperf jsperf.com/destructure-last/1
标签: ecmascript-6 destructuring