07-8. 배열내장 함수(shift, unshift, pop, push)

배열내장 함수

배열을 다룰 때 알고있으면 너무나 유용한 다양한 내장 함수들에 대하여 알아보겠습니다.

중요!

shift, unshift, pop, push 4개 모두 중요한점은 기존의 배열(원본의 데이터를)도 수정을 한다는 것입니다.

unshift & shift

unshift

unshift첫번째 원소에 배열의 새 원소를 추가합니다.

const numbers = [10, 20, 30, 40];
numbers.unshift(5);
console.log(numbers);

결과는 다음과 같습니다.

[5, 10, 20, 30, 40]

shift

shift첫번째 원소부터 배열에서 추출해줍니다. (추출하는 과정에서 배열에서 해당 원소는 사라집니다.)

const numbers = [10, 20, 30, 40];
const value = numbers.shift();

console.log(value);
console.log(numbers);

결과는 다음과 같습니다.

10
[20, 30, 40]

push & pop

push

push마지막 원소 배열에서 추가를 해줍니다.

const numbers = [10, 20, 30, 40];
numbers.push(50);
console.log(numbers)

결과는 다음과 같습니다.

50

pop

pop마지막 원소부터 배열에서 추출해줍니다. (추출하는 과정에서 배열에서 해당 원소는 사라집니다.)

const numbers = [10, 20, 30, 40];
const value = numbers.pop();

console.log(value);
console.log(numbers);

결과는 다음과 같습니다.

40
[10, 20, 30]

poppush 의 반대로 생각하시면 됩니다. push 는 배열의 맨 마지막에 새 항목을 추가하고, pop 은 맨 마지막 항목을 추출합니다.

Last updated