ES6 中解构获取数组的最后一个元素

问题描述 投票:0回答:19

CoffeeScript 中,这很简单:

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]

但也许这有点容易出现相差一的错误。啪啪声只能是解构中的最后一件事吗?

ecmascript-6 destructuring
19个回答
265
投票

console.log('last', [1, 3, 4, 5].slice(-1));
console.log('second_to_last', [1, 3, 4, 5].slice(-2));


73
投票

我相信 ES6 至少可以帮助解决这个问题:

[...arr].pop()

鉴于您的数组(arr)不是未定义的并且是一个可迭代元素(是的,甚至字符串也可以工作!!),它应该返回最后一个元素..即使对于空数组,它也不会改变它。它虽然创建了一个中间数组..但这应该不会花费太多。

您的示例将如下所示:

  console.log(  [...['a', 'b', 'program']].pop() );


61
投票

在 ES6/2015 中这是不可能的。标准只是没有提供这一点。

正如您在规范中看到的,

FormalParameterList
可以是:

  • a
    FunctionRestParameter
  • a
    FormalsList
    (参数列表)
  • a
    FormalsList
    ,然后是
    FunctionRestParameter

不提供

FunctionRestParameter
后跟参数。


61
投票

您可以解构反转的数组以接近您想要的。

const [a, ...rest] = ['a', 'b', 'program'].reverse();
  
document.body.innerHTML = 
    "<pre>"
    + "a: " + JSON.stringify(a) + "\n\n"
    + "rest: " + JSON.stringify(rest.reverse())
    + "</pre>";


44
投票

另一种方法是:

const arr = [1, 2, 3, 4, 5]
const { length, [length - 1]: last } = arr; //should be 5
console.log(last)


9
投票

您可以尝试使用应用于数组的对象解构来提取

length
,然后获取最后一项:例如:

const { length, 0: first, [length - 1]: last } = ['a', 'b', 'c', 'd']

// length = 4
// first = 'a'
// last = 'd'

更新

另一种方法Array.prototype.at()

at() 方法接受一个整数值并返回该索引处的项目,允许正整数和负整数...

const last = ['a', 'b', 'c', 'd'].at(-1)
// 'd'

8
投票

不一定是最高效的做法。但根据上下文,一个相当优雅的方式是:

const myArray = ['one', 'two', 'three'];
const theOneIWant = [...myArray].pop();

console.log(theOneIWant); // 'three'
console.log(myArray.length); //3


8
投票

获取数组的最后一个元素:

const [last,] = ['a', 'b', 'program'].reverse();

5
投票

这应该有效:

const [lastone] = myArray.slice(-1);

5
投票

const arr = ['a', 'b', 'c']; // => [ 'a', 'b', 'c' ]

const {
  [arr.length - 1]: last
} = arr;

console.log(last); // => 'c'


2
投票

不会破坏方式,但可以提供帮助。根据javascript文档和反向方法可以尝试这个:

const reversed = array1.reverse();
let last_item = reversed[0]

1
投票

您可以进一步将数组的

...rest
数组解构为
Object
,以获得其
length
属性并为最后一个索引构建一个 计算的属性名称

这甚至适用于参数破坏:

const a = [1, 2, 3, 4];

// Destruct from array ---------------------------
const [A_first, ...{length: l, [l - 1]: A_Last}] = a;
console.log('A: first: %o; last: %o', A_first, A_Last);     // A: first: 1; last: 4

// Destruct from fn param(s) ---------------------
const fn = ([B_first, ...{length: l, [l - 1]: B_Last}]) => {
  console.log('B: first: %o; last: %o', B_first, B_Last);   // B: first: 1; last: 4
};

fn(a);


1
投票

es6 允许类似的东西吗?

不,目前不可能,虽然我们将来可能会得到它,请参阅:

那么我们同时可以做什么?

我们想要:

const [...rest, last] = arr;
目前,最干净的方法可能是:

const arr = [1, 2, 3]; const [rest, last] = [arr.slice(0, -1), arr.at(-1)]; console.log({ rest, last });

记录:

{ rest: [ 1, 2 ], last: 3 }

arr
 未更改。它不会创建不必要的副本或中间数组。

请注意,

.at()

 是相当新的(截至撰写本文时):

另一种不使用

arr.at(-1)

的方法:

const arr = [1, 2, 3]; const rest = [...arr]; const last = rest.pop(); // <-- this mutates rest console.log({ rest, last });

其中记录:

{ rest: [ 1, 2 ], last: 3 }

arr
 自从我们首先进行了浅复制以来没有改变。它也不会创建不必要的 
arr
 副本或中间数组。然而,我不喜欢 
rest
 已经变异了。

如果向后兼容性很重要,那么即使在 ES3 中也可以:

var arr = [1, 2, 3]; var rest = arr.slice(); var last = rest.pop(); // <-- this mutates rest console.log({ rest: rest, last: last });

它不像

const [...rest, last] = arr;

那么优雅,但在我看来代码是可读且简单的。


0
投票
let a = [1,2,3] let [b] = [...a].reverse()
    

0
投票
这是我实际上能想到的最简单易懂的:

const first = [...arr]; const last = first.pop(); const others = first.join(', ');
    

0
投票
const arr = [1, 2, 3, 4, 5]; arr[arr.length - 1] = 6;

// => [1, 2, 3, 4, 6]


0
投票
非常简单的一个,

const arr = [1, 2, 3, 4, 5]; const last = arr.at(-1); console.log(last);
    

-1
投票
使用数组解构:“捕获”

array

、“
splice
d”数组 (
arrMinusEnd
) 和“
pop
ed”/“
slice
d”元素 (
endItem
)。

var [array, arrMinusEnd, endItem] = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"] .reduce( (acc, cv, idx, arr) => { if(idx<arr.length-1) acc[1].push(cv); else { acc[0]=arr; acc[2]=cv; }; return acc; }, [null,[],[]] ) ; console.log("array="); console.log(array); console.log("arrMinusEnd="); console.log(arrMinusEnd); console.log("endItem=\""+endItem+"\"");
.as-console-wrapper { max-height: 100% !important; top: 0; }


-1
投票
毫无疑问,问题是关于 JavaScript 数组的

解构,我们知道不可能通过使用解构赋值来获得数组的最后一项,有一种方法可以做到不可变,请参阅以下内容:

const arr = ['a', 'b', 'c', 'last']; ~~~ const arrLength = arr.length - 1; const allExceptTheLast = arr.filter( (_, index) => index !== arrLength ); const [ theLastItem ] = arr.filter( (_, index) => index === arrLength );
我们不会改变 

arr

 变量,但仍然拥有除最后一项之外的所有数组成员作为数组,并单独拥有最后一项。

© www.soinside.com 2019 - 2024. All rights reserved.