
스택에 자료를 넣는다: push()
스택에서 자료를 뺀다: pop()
큐에 자료를 넣는다: push()
큐에서 자료를 뺀다: shift()
const animals = ['pigs', 'goats', 'sheep'];
const count = animals.push('cows');
console.log(count); // 4
console.log(animals); // ["pigs", "goats", "sheep", "cows"]
animals.push('chickens', 'cats', 'dogs');
console.log(animals);
// ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]
apply()를 이용해 두 개의 배열을 합칠 수 있다.
var vegetables = ['설탕당근', '감자'];
var moreVegs = ['셀러리', '홍당무'];
// 첫번째 배열에 두번째 배열을 합친다.
// vegetables.push('셀러리', '홍당무'); 하는 것과 동일하다.
Array.prototype.push.apply(vegetables, moreVegs);
console.log(vegetables); // ['설탕당근', '감자', '셀러리', '홍당무']
const array1 = [1, 2, 3];
console.log(array1.unshift(4, 5)); // 5
console.log(array1); // [4, 5, 1, 2, 3]
pop()을 호출하면 undefined를 반환한다.const 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"]
shift()를 호출하면 undefined를 반환한다.var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];
console.log(myFish); // [angel, clown, mandarin, surgeon]
var shifted = myFish.shift();
console.log(myFish); // [clown, mandarin, surgeon]
console.log(shifted); // angel
while 반복문 안에서 shift() 사용하기
shift() 메서드는 while문의 조건으로 사용되기도 한다. 아래 코드에서는 while 문을 한번 돌 때마다 배열의 다음 요소를 제거하고, 이는 빈 배열이 될 때까지 반복된다.
var names = ["Andrew", "Edward", "Paul", "Chris" ,"John"];
while( (i = names.shift()) !== undefined ) {
console.log(i);
}
// Andrew, Edward, Paul, Chris, John