142

在咖啡脚本中,这很简单:

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 只能是解构中的最后一件事吗?

4

16 回答 16

253

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

于 2016-10-19T07:06:29.243 回答
71

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

[...arr].pop()

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

您的示例将如下所示:

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

于 2016-05-25T16:23:49.367 回答
54

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

正如您在规范中看到的那样,FormalParameterList可以是:

  • 一个FunctionRestParameter
  • a FormalsList(参数列表)
  • 一个FormalsList,后跟一个FunctionRestParameter

FunctionRestParameter不提供后跟参数。

于 2015-10-11T11:53:17.020 回答
49

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

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

于 2016-09-24T11:57:30.860 回答
35

另一种方法是:

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

于 2019-11-08T16:35:42.877 回答
8

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

const [last,] = ['a', 'b', 'program'].reverse();
于 2020-09-30T12:35:38.360 回答
8

不一定是最高效的做法。但根据上下文,一种非常优雅的方式是:

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

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

于 2017-11-01T01:36:09.380 回答
4

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

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

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

于 2019-07-08T15:24:56.617 回答
4

这应该有效:

const [lastone] = myArray.slice(-1);
于 2019-07-04T20:07:53.237 回答
3

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

const reversed = array1.reverse();
let last_item = reversed[0]
于 2020-06-27T17:48:14.663 回答
1
let a = [1,2,3]
let [b] = [...a].reverse()
于 2020-06-01T18:40:59.373 回答
1

您可以进一步将数组的数组破坏...restObject,以获取其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);

于 2021-11-28T19:59:26.043 回答
1

您可以尝试使用应用于数组的对象解构length来提取然后获取最后一项:例如:

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

// length = 4
// first = 'a'
// last = 'd'
于 2022-02-12T03:52:22.193 回答
0

你可以试试这个技巧:

let a = ['a', 'b', 'program'];
let [last] = a.reverse();
a.reverse();
console.log(last);
于 2019-10-11T10:05:56.170 回答
0

当然,问题是关于JavaScript数组的解构,我们知道使用解构赋值不可能拥有数组的最后一项,有一种方法可以做到不可变,请参见以下内容:

const arr = ['a', 'b', 'c', 'last'];

~~~
const arrDepth = arr.length - 1;

const allExceptTheLast = arr.filter( (dep, index) => index !== arrDepth && dep );
const [ theLastItem ] = arr.filter( (dep, index) => index === arrDepth && dep );

我们不改变arr变量,但仍然将除最后一项之外的所有数组成员作为一个数组,并分别拥有最后一项。

于 2020-02-14T00:24:44.533 回答
0

使用数组解构:“捕获” array、“ spliced”数组(arrMinusEnd)和“ poped”/“ sliced”元素(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; }

于 2020-09-23T19:44:10.107 回答