본문 바로가기
js

배열조작하기 (push,unshift,pop)

by 땅빵주 2021. 1. 24.

1. 요소추가하기 

 

cities라는 변수에 빈 배열을 할당한 후 원하는 위치 마음대로 요소를 할당할 수 있다.

let cities = [];

cities[0] = "서울";
citiees[6] = "부산";


console.log(cities);

 

아무것도 할당하지 않는다면 undefined라고 출력된다. 

["서울", undefined, undefined,undefined,undefined,undefined,"부산"]

 

만약에 수정하고 싶을땐 아래와 같이 배열의 인덱스에 접근하여 값을 할당할 수 있다

 

 

cities[0] = "경기도" ;


console.log(cities); 

// ["경기도", undefined, undefined,undefined,undefined,undefined,"부산"]

 

2. push 와 unshift

 

push 는 배열의 맨 끝에 추가해주는 함수이고

unshift는 배열의 맨 앞에 추가해주는 함수이다 

 

 

let cities = [];

cities.push("경주","전주");
cities.unshift("서울","부산");


console.log(cities);



//[ "서울","부산","경주","전주" ]

 

 

배열 조작 방법은 두 가지가 있다 

첫번째, index로 접근하여 수정이나 추가하기

 

let day = ['m', 's', 'w', 't'];
day[1] = 't';
day[4] = 'f';
day[5] = 's'; 

console.log(day);

//[ m, t, w, t, f, s ]

 

두번째, push와 unshift로 추가하기

 

let month = [1, 2, 3, 4]

month.push(5); 
month.unshift("오늘은 몇월일까요?");

console.log(month)

//['오늘은 몇월일까요?',1,2,3,4,5 ]

 

3. pop함수

 

pop함수는 마지막 요소가 제거되고, 마지막 요소의 값을 반환한다

let month = [1, 2, 3, 4]

month. pop ();  //  4
console.log(month) // [1,2,3] 

 

 

'js' 카테고리의 다른 글

"String " ( split, slice )  (0) 2021.02.07
Instagram 로그인버튼 색 바꾸기  (0) 2021.01.24
반복문 - for문  (0) 2021.01.19
객체(Object)  (0) 2021.01.05
공부하면서 궁금한점 끄적이는 페이지.  (0) 2020.12.29

댓글