Posts

[JS] 원본 배열을 변경하는 메소드

목차7

아래 메소드들은 원본 배열을 변경하는 메소드들이다.

Array.prototype.pop()

배열에서 마지막 요소를 제거하고 해당 요소를 반환한다.

코드
const array = [1, 2, 3];
const poppedElement = array.pop(); // 3
console.log(array); // [1, 2]

Array.prototype.push()

배열 끝에 하나 이상의 요소를 추가하고 배열의 새로운 길이를 반환한다.

코드
const array = [1, 2];
const newLength = array.push(3, 4); // 4
console.log(array); // [1, 2, 3, 4]

Array.prototype.reverse()

배열의 순서를 뒤집는다.

코드
const array = [1, 2, 3];
array.reverse();
console.log(array); // [3, 2, 1]

Array.prototype.shift()

배열에서 첫 번째 요소를 제거하고 해당 요소를 반환한다.

코드
const array = [1, 2, 3];
const shiftedElement = array.shift(); // 1
console.log(array); // [2, 3]

Array.prototype.sort()

배열의 요소를 정렬한다.

코드
const array = [3, 1, 2];
array.sort();
console.log(array); // [1, 2, 3]

Array.prototype.splice()

배열에서 요소를 제거하거나 새로운 요소를 추가한다.

코드
const array = [1, 2, 3];
const removedElements = array.splice(1, 1); // [2]
console.log(array); // [1, 3]

array.splice(1, 0, 'a', 'b'); // insert 'a', 'b' starting from index 1
console.log(array); // [1, 'a', 'b', 3]

Array.prototype.unshift()

배열의 시작 부분에 하나 이상의 요소를 추가하고 배열의 새로운 길이를 반환한다.

코드
const array = [1, 2];
const newLength = array.unshift(3, 4); // 4
console.log(array); // [3, 4, 1, 2]

반응형