Array.prototype.at()

KIXIAM·2022년 12월 29일
0

TIL

목록 보기
21/22
post-thumbnail

TIL_221229

배열에서 몇번째 값을 찾을 때 array[index] 로 보통 값을 찾는다. 하지만 배열이 갖고 있는 요소들이 많은 경우에 뒤에서 찾고자 할 때가 편할 때가 있다.


하지만 !

conat array1 = [1, 2, 3, 4, 5];
console.log(array1[-1]); // undefined

출력값 : undefinded (기대했던 5가 나오지 않는다.)


음수 값이 인식이 되지 않는다.
그럴땐 at() 을 사용하여 음수를 인식하여 뒤에 값을 쉽게 가져올 수 있다.

const array1 = [5, 12, 8, 130, 44];
let index = 2;
console.log(`${index} 번째 숫자는 ${array1[index]}`);
console.log(`${index} 번째 숫자는 ${array1.at(index)}`);
index = -2;
console.log(`${index} 번째 숫자는 ${array1[index]}`); 
console.log(`${index} 번째 숫자는 ${array1.at(index)}`);

출력값

배열 객체의 property 내에 있는 at 메서드를 이용하여 기존에는 불러오지 못했던 음수인식을 가능하게 만드는 것을 눈으로 확인했다. 이제 뒤에 값도 편하게 불러오자!

profile
Project Oriented Learning 🔥

0개의 댓글