[Javascript 코테 대비] 스택(Stack)과 큐(Queue): array 자료 넣고 빼기

허지예·2023년 3월 11일
0
post-thumbnail

스택(Stack)

  • 스택에 자료를 넣는다: push()

  • 스택에서 자료를 뺀다: pop()

큐(Queue)

  • 큐에 자료를 넣는다: push()

  • 큐에서 자료를 뺀다: shift()

Array에서 자료 넣고 빼기

push(): 배열 끝에 자료를 넣는다

  • 배열의 끝에 하나 이상의 요소를 추가하고 배열의 새로운 길이를 반환한다.
  • 매개변수를 여러 개 작성하면 여러 개를 한꺼번에 배열에 추가할 수 있다.
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); // ['설탕당근', '감자', '셀러리', '홍당무']

unshift(): 배열 앞에 자료를 넣는다

  • 배열의 앞에 하나 이상의 요소를 추가하고 배열의 새로운 길이를 반환한다.
  • 매개변수를 여러 개 작성하면 여러 개를 한꺼번에 배열에 추가할 수 있다.
const array1 = [1, 2, 3];

console.log(array1.unshift(4, 5)); // 5

console.log(array1); // [4, 5, 1, 2, 3]

pop(): 배열 끝에 자료를 하나 뺀다

  • 배열의 마지막 요소를 제거하고 그 요소를 반환한다.
  • 빈 배열에 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(): 배열 앞에 자료를 하나 뺀다

  • 배열의 첫 번째 요소를 제거하고, 제거된 요소를 반환한다.
  • 빈 배열에 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
profile
대학생에서 취준생으로 진화했다가 지금은 풀스택 개발자로 2차 진화함

0개의 댓글