Array.prototype.push() 메서드

Array.prototype.push() 메서드

push()Array 인스턴스의 메서드로, 지정된 요소들을 배열의 끝에 추가하고 배열의 새 길이를 반환합니다. 배열을 다룰 때 가장 흔히 쓰이는 변경(mutating) 메서드 중 하나로, 스택(stack) 및 컬렉션 관리의 기반이 됩니다.

출처: Array.prototype.push() - MDN Web Docs

본문

개요

push() 메서드는 배열 끝에 지정된 요소들을 추가합니다. 여러 요소를 한 번에 추가할 수 있으며, 추가 후 배열의 새 length 값을 반환합니다.

기본적인 사용 예는 다음과 같습니다.

const animals = ["pigs", "goats", "sheep"];

const count = animals.push("cows");
console.log(count);
// Expected output: 4
console.log(animals);
// Expected output: Array ["pigs", "goats", "sheep", "cows"]

animals.push("chickens", "cats", "dogs");
console.log(animals);
// Expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]

구문(Syntax)

push()
push(element1)
push(element1, element2)
push(element1, element2, /* …, */ elementN)

매개변수

  • element1, …, elementN — 배열의 끝에 추가할 요소(들)입니다.

반환값 — 메서드가 호출된 객체의 새 length 프로퍼티입니다.

설명(Description)

push() 메서드는 배열에 값을 추가합니다.

Array.prototype.unshift()push()와 유사한 동작을 하지만 배열의 시작에 적용됩니다.

push() 메서드는 변경(mutating) 메서드입니다. this의 길이와 내용을 변경합니다. this의 값은 그대로 두고 요소들이 끝에 추가된 새 배열을 반환받고 싶다면 arr.concat([element0, element1, /* ... ,*/ elementN])을 대신 사용할 수 있습니다. 요소들이 추가 배열로 감싸져야 합니다 — 그렇지 않으면 요소 자체가 배열일 때 concat()의 동작 때문에 단일 요소로 푸시되는 대신 펼쳐지기 때문입니다.

push() 메서드는 일반적(generic)입니다. this 값이 length 프로퍼티와 정수 키 프로퍼티를 갖기만 하면 됩니다. 문자열도 유사 배열이지만, 문자열은 불변(immutable)이므로 이 메서드를 문자열에 적용하는 것은 적절하지 않습니다.

예제

배열에 요소 추가하기 — 다음 코드는 두 요소를 가진 sports 배열을 만들고 두 요소를 추가합니다. total 변수에는 배열의 새 길이가 담깁니다.

const sports = ["soccer", "baseball"];
const total = sports.push("football", "swimming");

console.log(sports); // ['soccer', 'baseball', 'football', 'swimming']
console.log(total); // 4

두 배열 병합하기전개 구문을 사용해 두 번째 배열의 모든 요소를 첫 번째 배열로 푸시할 수 있습니다.

const vegetables = ["parsnip", "potato"];
const moreVegs = ["celery", "beetroot"];

// Merge the second array into the first one
vegetables.push(...moreVegs);

console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot']

두 배열 병합은 concat() 메서드로도 할 수 있는데, 이는 원본에 추가하는 대신 결합된 새 배열을 만듭니다. 전개 구문은 배열의 요소 수가 엔진이 허용하는 함수 인자의 최대 수보다 적을 때만 동작합니다. 더 긴 배열의 경우 concat()을 쓰거나 루프에서 push()를 여러 번 호출하십시오.

배열이 아닌 객체에서 push() 호출하기push() 메서드는 thislength 프로퍼티를 읽습니다. 그런 다음 push()에 전달된 인자들로 length부터 시작하는 각 인덱스를 설정합니다. 마지막으로 length를 이전 길이에 푸시된 요소 수를 더한 값으로 설정합니다.

const arrayLike = {
  length: 3,
  unrelated: "foo",
  2: 4,
};
Array.prototype.push.call(arrayLike, 1, 2);
console.log(arrayLike);
// { '2': 4, '3': 1, '4': 2, length: 5, unrelated: 'foo' }

const plainObj = {};
// There's no length property, so the length is 0
Array.prototype.push.call(plainObj, 1, 2);
console.log(plainObj);
// { '0': 1, '1': 2, length: 2 }

객체를 유사 배열 방식으로 사용하기 — 앞서 언급했듯이 push는 의도적으로 일반적(generic)이며, 이를 활용할 수 있습니다. Array.prototype.push는 객체에서도 잘 동작합니다. 주의할 점은 객체 컬렉션을 저장하기 위해 배열을 만들지 않고, 컬렉션을 객체 자체에 저장한 뒤 Array.prototype.pushcall을 사용해 메서드가 배열을 다루는 것처럼 속이는 방식입니다. JavaScript가 실행 컨텍스트를 원하는 대로 설정할 수 있게 해 주기 때문에 그대로 동작합니다.

const obj = {
  length: 0,

  addElem(elem) {
    // obj.length is automatically incremented
    // every time an element is added.
    [].push.call(this, elem);
  },
};

// Let's add some empty objects just to illustrate.
obj.addElem({});
obj.addElem({});
console.log(obj.length); // 2

obj가 배열이 아님에도 push 메서드가 실제 배열을 다루듯 objlength 프로퍼티를 성공적으로 증가시켰음을 확인할 수 있습니다.

더 알아보기