본문 바로가기
Language/JavaScript (Modern)

[ES6+] at() - 문자열/배열의 특정 인덱스 위치에 있는 값 가져오기 (ft. 음수)

by 썸머워즈 2022. 7. 13.
반응형

배열 또는 문자열에서 특정 인덱스에 위치한 값을 가져오는 방법은 매우 간단한데, 좀 더 복잡하게 뒤에서부터 몇 번째 같은 경우처럼 처리하기 난감한 상황들이 간혹 존재한다. (대체적으로 "전체 길이 - 1"로 처리를 해왔었던 것 같다.)

 

하지만 드디어 스크립트에서도 양수와, 음수를 가지고 특정 인덱스에 접근하는 걸 도와주는 메서드가 생겼다.

각각 String.prototype.at() 와 Array.prototype.at()이며, 한번 알아가 보도록 하자.

 

▷ 구문

.at(index)

index: 반환할 배열 요소의 인덱스(위치)이다. 음수 인덱스를 전달할 때 배열 끝에서 상대 인덱싱을 지원한다. (즉, 음수를 사용하는 경우에는 배열의 끝에서부터 역으로 위치를 계산해서 가져온다.)

 

예제를 통해 알아보자.


▷ 예제1) .at() 메서드 기본 사용법

// Our array with items
const cart = ["apple", "banana", "pear"];
let myString = "mine-it-record";

// A function which returns the last item of a given array
const returnLast = (item) => item.at(-1);

// Get the last item of our array 'cart'
const item1 = returnLast(cart);
console.log(item1); // 'pear'

// Add an item to our 'cart' array
cart.push("orange");
const item2 = returnLast(cart);
console.log(item2); // 'orange'

// Get the last item of our string 'myString'
const item3 = returnLast(myString);
console.log(item3); // 'd'

// Add an item to our 'myString' string
myString += "❗";
const item4 = returnLast(myString);
console.log(item4); // '❗'

참고: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/at

 

String.prototype.at() - JavaScript | MDN

The at() method takes an integer value and returns a new String consisting of the single UTF-16 code unit located at the specified offset. This method allows for positive and negative integers. Negative integers count back from the last string character.

developer.mozilla.org

참고: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at

 

Array.prototype.at() - JavaScript | MDN

The at() method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array.

developer.mozilla.org

반응형


댓글

TOP