자바스크립트에서 Negative Index 사용하기

DriedWoo·2022년 10월 18일
0
post-thumbnail

Negative Indexing이란?

원소 여러 개가 있는 배열이 있을 때, 배열에 들어 있는 원소 개수에 상관없이 맨 뒤에서부터 인덱싱하는 것을 뜻한다.

파이썬에서의 Negative Indexing

기존에 이 기능을 지원했던 언어로는 파이썬이 있다. 파이썬에서 Negative Index를 사용하는 방법은 다음과 같다.

ex_ㅣist = [1, 2, 3, 4, 5]
print(ex_ㅣist[-1]) # 5
print(ex_ㅣist[-2:]) # [4, 5]

매우 간편하게 사용할 수 있다.

반면 자바스크립트에서는

ES2021까지, 자바스크립트에는 편리한 Negative Indexing 기능이 없었다.

기존 JS에서 Negative Index를 사용하려면 다음과 같이 해야 했다.

const exList = [1, 2, 3, 4, 5];

console.log(exList[exList.length - 1]); // 5
console.log(exList.slice(-1)[0]); // 5
console.log(exList.reverse()[0]); // 5

모두 편법에 가깝고, 직관적이지 않다.

Array.prototype.at()

ES2022에서 Array.prototype.at() 함수가 발표되어, 훨씬 편리하게 Negative Index를 사용할 수 있게 되었다.

const exList = [1, 2, 3, 4, 5];

console.log(exList.at(-1)); // 5

이렇게 간단하게 사용 가능하다.

console.log(exList.at(-10)); // undefined

배열에 없는 값을 인자로 넣었을 경우 undefined를 반환한다.

profile
mindle

0개의 댓글