解析以获取es6中数组的最后一个元素 [英] Destructuring to get the last element of an array in es6
本文介绍了解析以获取es6中数组的最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
咖啡> a = ['a','b','program']
['a','b','program']
coffee> [_...,b] = a
['a','b','program']
coffee> b
'程序'
es6是否允许类似的东西?
> const [,b] = [1,2,3]
'use strict'
> b //它有第二个元素,而不是最后一个元素!
2
> const [... butLast,last] = [1,2,3]
SyntaxError:repl:Unexpected token(1:17)
> 1 | const [... butLast,last] = [1,2,3]
| ^
在Parser.pp.raise(C:\Users\user\AppData\Roaming\\\
pm\\\
ode_modules\babel\\\
ode_modules\babel-core\\\
ode_modules\babylon\\ \\ lib\parser\location.js:24:13)
当然可以做到es5方式 -
const a = b [b.length - 1]
但是也许这有点容易出现一个错误。这个破坏只能是破坏的最后一件事吗?
解决方案
在ES6 / 2015中是不可能的。标准只是没有提供。
正如你在规范, FormalParameterList
可以是:
- a
FunctionRestParameter
- a
FormalsList
(参数列表) - a
FormalsList
,后跟一个FunctionRestParameter
拥有 FunctionRestParameter
没有提供。
这是ES6 / 2015不如CoffeeScript的很多例子之一。
In coffeescript this is straightforward:
coffee> a = ['a', 'b', 'program']
[ 'a', 'b', 'program' ]
coffee> [_..., b] = a
[ 'a', 'b', 'program' ]
coffee> b
'program'
Does es6 allow for something similar?
> 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)
Of course I can do it the es5 way -
const a = b[b.length - 1]
But maybe this is a bit prone to off by one errors. Can the splat only be the last thing in the destructuring?
解决方案
It is not possible in ES6/2015. The standard just doesn't provide for it.
As you can see in the spec, the FormalParameterList
can either be:
- a
FunctionRestParameter
- a
FormalsList
(a list of parametes) - a
FormalsList
, followed by aFunctionRestParameter
Having FunctionRestParameter
followed by parameters is not provided.
This is one of many examples how ES6/2015 is inferior to CoffeeScript.
这篇关于解析以获取es6中数组的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文