在CoffeeScript中,这很简单:
ES6允许类似的功能吗?
当然,我可以用ES5的方式来做。
但也许这样容易出现一点偏差。展开运算符只能在解构中的最后一个位置吗?
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]
但也许这样容易出现一点偏差。展开运算符只能在解构中的最后一个位置吗?
...
的行为,尤其是它只能在解构或参数列表中作为最后一项使用。对于从Coffeescript转入es6的人来说,这可能会产生反直觉的感觉,因此这个问题有潜在的用处。 - George Simms[1,2,3].slice(-1)
之外,你甚至不能解构等同于[1,2,3].slice(0, -1)
的操作。这些是常见的操作。ES6 解构有点像一个笑话! - user5536315const [c] = ['bee'].slice(-1)
有什么问题吗? - Andre Figueiredo