본문 바로가기

Programing/JavaScript

.shift() .pop() / 배열에서 요소제거

Array.prototype.shift()

shift() 메서드는 배열에서 첫 번째 요소를 제거하고, 제거된 요소를 반환합니다. 이 메서드는 배열의 길이를 변하게 합니다.

 

1
2
3
4
5
6
7
8
9
var array1 = [123];
 
var firstElement = array1.shift();
 
console.log(array1);
// expected output: Array [2, 3]
 
console.log(firstElement);
// expected output: 1
cs

 

return             배열에서 제거한 요소. 빈 배열의 경우 undefined 를 반환합니다. 

 

 

Array.prototype.pop() / mutable (배열변함)

pop() 메서드는 배열에서 마지막 요소를 제거하고 그 요소를 반환합니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
var plants = ['broccoli''cauliflower''cabbage''kale''tomato'];
 
console.log(plants.pop());
// expected output: "tomato"
 
console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]
 
plants.pop();
 
console.log(plants);
// expected output: Array ["broccoli", "cauliflower", "cabbage"]
 
cs

 

return             배열에서 제거한 요소. 빈 배열의 경우 undefined 를 반환합니다. 

console.log(plants.pop()); 했을 때 리턴값은 'tomato'