[ecmascript-6] es6에서 배열의 마지막 요소를 얻기위한 구조 해제

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]

그러나 아마도 이것은 하나의 오류로 인해 약간 벗어나기 쉽습니다. 표시가 구조 해체의 마지막 일뿐일까요?



답변

ES6 / 2015에서는 불가능합니다. 표준은 그것을 제공하지 않습니다.

당신이 볼 수 있듯이 사양 의가 FormalParameterList될 수 있습니다 :

  • FunctionRestParameter
  • a FormalsList(매개 변수 목록)
  • a FormalsList다음에 aFunctionRestParameter

FunctionRestParameter파라미터 뒤에 제공되지 않는다.


답변

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


답변

나는 ES6가 적어도 도움이 될 수 있다고 믿습니다.

[...arr].pop()

배열 (arr)이 정의되지 않고 반복 가능한 요소 (예, 문자열도 작동합니다 !!)가 주어지면 빈 배열에 대해서도 마지막 요소를 반환해야하며 변경하지도 않습니다. 그래도 중간 배열을 생성하지만 비용이 많이 들지는 않습니다.

귀하의 예는 다음과 같습니다.

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


답변

역 배열을 분해하여 원하는 것에 근접 할 수 있습니다.

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

document.body.innerHTML =
    "<pre>"
    + "a: " + JSON.stringify(a) + "\n\n"
    + "rest: " + JSON.stringify(rest.reverse())
    + "</pre>";


답변

또 다른 접근 방식은 다음과 같습니다.

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


답변

반드시 가장 성능이 좋은 방법은 아닙니다. 그러나 상황에 따라 매우 우아한 방법은 다음과 같습니다.

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

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


답변

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

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

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