[JS] 배열의 앞과 뒤에 요소를 추가하는 메서드: push(), unshift()

cabbage·2023년 1월 16일

JS

목록 보기
12/43
post-thumbnail

배열에 데이터를 추가하려면 push(), unshift() 메서드를 사용할 수 있다.

Array.prototype.push()

push() 메서드는 배열의 가장 뒤에 하나 이상의 요소를 추가하고, 배열의 새로운 길이를 반환한다.

const arr = ["a", "b", "c"];
const count = arr.push("d");

console.log(count);  // 4
console.log(arr); // ["a", "b", "c", "d"]

arr.push("e", "f", "g");
console.log(arr); // ["a", "b", "c", "d", "e", "f", "g"]

Array.prototype.unshift()

unshift() 메서드는 배열의 시작에 하나 이상의 요소를 추가하고, 배열의 새로운 길이를 반환한다.

const arr = [1, 2, 3];
let count = arr.unshift(4);
count = arr.unshift(5);

console.log(count); // 5
console.log(arr);   // [5, 4, 1, 2, 3]

arr.unshift(6, 7);

console.log(arr);  // [6, 7, 5, 4, 1, 2, 3]

참고

profile
캐비지 개발 블로그입니다. :)

0개의 댓글