Array.prototype.at()

So'sCode·2022년 1월 21일
0

Method 정리

목록 보기
1/8
post-thumbnail

📌 at() 메서드란

정수 값을 받아, 배열에서 해당 값에 해당하는 인덱스의 요소를 반환한다.

  • 양수 값, 음수값 지정 가능
  • 음수 값일 경우 배열의 뒤부터 인덱스를 센다.
  • 사용 방법 : 배열.at(index)

💻 예제1. 양수 값을 지정했을 경우

const astro = [Mj,진진,차은우,문빈,라키,윤산하];

let first = 5;

console.log(`My favorite member is the ${first}th member ${astro.at(first)}`);
//"My favorite member is the 5th member 윤산하"

💻 예제2. 음수 값을 지정했을 경우

// 대상 배열
const astro= ['Mj' '진진', '차은우'];

// 주어진 배열의 마지막 요소를 반환하는 함수
function returnLast(arr) {
  return arr.at(-1);
}

// 위의 배열 'astro'에서 마지막 요소를 가져옴
const item1 = returnLast(astro);
console.log(item1); // '차은우' 기록

// 위의 배열 'astro'에 요소를 추가함
astro.push('문빈');
const item2 = returnLast(astro);
console.log(item2); // '문빈' 기록

출처 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/at

profile
이왕하는거미루지말고하자.

0개의 댓글