Geo*_*mms 93 destructuring ecmascript-6
在coffeescript中这很简单:
coffee> a = ['a', 'b', 'program']
[ 'a', 'b', 'program' ]
coffee> [_..., b] = a
[ 'a', 'b', 'program' ]
coffee> b
'program'
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
当然我可以用es5方式做到 -
const a = b[b.length - 1]
Run Code Online (Sandbox Code Playgroud)
但也许这有点容易因一个错误而消失.splat只能是解构中的最后一件事吗?
Rya*_*ang 191
console.log('last', [1, 3, 4, 5].slice(-1));
console.log('second_to_last', [1, 3, 4, 5].slice(-2));Run Code Online (Sandbox Code Playgroud)
sho*_*sel 35
我相信ES6至少可以帮助解决这个问题:
[...arr].pop()
Run Code Online (Sandbox Code Playgroud)
鉴于你的数组(arr)没有未定义和一个可迭代的元素(是的,甚至字符串工作!!),它应该返回最后一个元素..即使是空数组,它也不会改变它.虽然它创建了一个中间数组但是不应该花费太多.
您的示例将如下所示:
console.log( [...['a', 'b', 'program']].pop() );Run Code Online (Sandbox Code Playgroud)
Jef*_*ton 32
你可以解构反转阵列以接近你想要的.
const [a, ...rest] = ['a', 'b', 'program'].reverse();
document.body.innerHTML =
"<pre>"
+ "a: " + JSON.stringify(a) + "\n\n"
+ "rest: " + JSON.stringify(rest.reverse())
+ "</pre>";Run Code Online (Sandbox Code Playgroud)
Den*_*rny 29
另一种方法是:
const arr = [1, 2, 3, 4, 5]
const { length, [length - 1]: last } = arr; //should be 5
console.log(last)Run Code Online (Sandbox Code Playgroud)
Ser*_*ack 10
您可以尝试使用应用于数组的对象解构来提取length然后获取最后一项:例如:
const { length, 0: first, [length - 1]: last } = ['a', 'b', 'c', 'd']
// length = 4
// first = 'a'
// last = 'd'
Run Code Online (Sandbox Code Playgroud)
另一种方法Array.prototype.at()
at() 方法采用整数值并返回该索引处的项目,允许正整数和负整数...
const last = ['a', 'b', 'c', 'd'].at(-1)
// 'd'
Run Code Online (Sandbox Code Playgroud)
小智 5
不一定是最高效的方式。但是根据上下文,一种相当优雅的方式是:
const myArray = ['one', 'two', 'three'];
const theOneIWant = [...myArray].pop();
console.log(theOneIWant); // 'three'
console.log(myArray.length); //3Run Code Online (Sandbox Code Playgroud)
const arr = ['a', 'b', 'c']; // => [ 'a', 'b', 'c' ]
const {
[arr.length - 1]: last
} = arr;
console.log(last); // => 'c'Run Code Online (Sandbox Code Playgroud)
获取数组的最后一个元素:
const [last,] = ['a', 'b', 'program'].reverse();
Run Code Online (Sandbox Code Playgroud)