[Javascript] Array Method(1) - push, pop, shift, unshift, splice

안셩·2024년 7월 29일

복습내용

목록 보기
7/27

배열메서드

배열메서드에 들어가기 전,
function vs method : 호출의 주체가 있느냐 없느냐!
(명확하면 function / 명확하지 않으면 method)

1) push

: 배열의 맨 마지막 요소 뒤에 요소 추가

const arr = [30, 1, 2, 5, 40];
const newArr = arr.push(100);
console.log(newArr); // 6

push 메서드는 배열의 길이를 반환하기 때문에
console.log(newArr); // 6을 나타낸다.

-> 변경된 배열을 반환하고 싶다면,
arr.push(100); 한 후, console.log(arr);를 하면 된다.
원본배열 arr가 변경된 arr를 바로 보여줌.

const arr = [30, 1, 2, 5, 40];
arr.push(100); // [30, 1, 2, 5, 40, 100]

2) pop

: 튀어나오게 함.

① 배열의 맨 마지막 요소 제거

const arr = [30, 1, 2, 5, 40];

arr.push(100); // // [30, 1, 2, 5, 40, 100]
arr.pop();
console.log(arr); // [30, 1, 2, 5, 40]

: 모두 배열 arr에서 진행되므로 배열 arr를 console로 나타내면 요소 100을 추가했다가 제거한 배열(=원본 배열)을 표현할 수 있다.

② 배열의 맨 마지막 요소 반환

const arr = [30, 1, 2, 5, 40];

arr.push(100); // [30, 1, 2, 5, 40, 100]
const test = arr.pop();
console.log(test); // 100

3) shift

: 배열의 첫 번째 요소 삭제

const arr = [30, 1, 2, 5, 40];

arr.shift();
console.log(arr); // [1, 2, 5, 40]

4) unshift

: 배열의 첫 번째에 요소 추가

const arr = [30, 1, 2, 5, 40];

arr.unshift(17);
console.log(arr); // [17, 30, 1, 2, 5, 40]

5) splice

: 배열의 a번째부터 b개까지 c로 대체(: 배열의 a번째부터 b개까지 c로 대체)

const arr = [30, 1, 2, 5, 40];

arr.splice(2, 1, 17);
console.log(arr); // [30, 1, 17, 5, 40]

-> 배열의 2번째 위치인 요소 2부터 1개니까 숫자 2만 17로 대체

profile
24.07.15 프론트엔드 개발 첫 걸음

0개의 댓글