[Javascript] 배열요소 조작 메서드
push메서드
배열의 맨 뒤에 새로운 요소를 추가하는 메서드
배열이름.push(추가할요소내용);
let arr1 = ['red', 'blue', 'green'];
arr1.push('yellow', 'cyan', 'black');
console.log(arr1);
→결괏값:(6) ['red', 'blue', 'green', 'yellow', 'cyan', 'black']
push메서드는 요소를 추가한 다음 변환된 배열의 길이를 반환함
pop메서드
배열의 맨 뒤에 있는 요소를 제거하고 그 결괏값을 반환
배열이름.pop();
let arr2 = ['red', 'blue', 'green'];
const popped = arr2.pop();
console.log(popped);
→결괏값: green
console.log(arr2);
→결괏값: (2) ['red', 'blue']
shift메서드
배열의 맨 앞에 있는 요소를 제거하고 반환
배열이름.shift();
let arr3 = ['red', 'blue', 'green'];
const shifted = arr3.shift();
console.log(shifted);
→결괏값: red
console.log(arr3);
→결괏값: (2) ['blue', 'green']
unshift메서드
배열의 맨 앞에 새로운 요소를 추가하는 메서드
배열이름.unshift(새로 추가할 요소 내용);
요소를 추가한 다음 변환된 배열의 길이를 반환함
let arr4 = ['red', 'blue', 'green'];
arr4.unshift('black');
console.log(arr4);
결괏값: (4) ['black', 'red', 'blue', 'green']
slice메서드
배열의 특정 범위를 잘라내서 새로운 배열로 반환
배열이름.slice(자르기 시작할 인덱스, 잘라낼 범위의 끝 인덱스의 +1);
slice로 잘라내도 원본 값은 변하지 않음
let arr5 = ['red', 'blue', 'green'];
let sliced = arr5.slice(1, 3);
console.log(sliced);
→ 결괏값: ['blue', 'green']
이때 끝까지 자를 거면 2번째 인수 제외해도 됨
let sliced2 = arr5.slice(2);
console.log(sliced);
→ 결괏값: ['blue', 'green']
배열을 뒤에서부터 자르고 싶으면 음수값으로 표현
let sliced3 = arr5.slice(-1);
console.log(sliced3);
→ 결괏값: ['green']
concat메서드
두 개의 서로 다른 배열을 이어 붙어서 새로운 배열을 반환
배열이름.concat(이어붙일 배열이름);
let arr6 = ['red', 'blue', 'green'];
let arr7 = ['black', 'white'];
let arr8 = arr6.concat(arr7);
console.log(arr8);
→ 결괏값: (5) ['red', 'blue', 'green', 'black', 'white']