TIL | Array Methods(Push, Pop, Shift, Unshift)

ryan·2020년 11월 17일
1

JavaScript

목록 보기
6/23
post-thumbnail

🚍 Array Methods

  • push - add to end
  • pop - remove from end
  • shift - remove from start
  • unshift - add to start

👈 push() - add to end

let movieLine = ["tom", "nance"];

movieLine[2] = "pablo";
movieLine; // ["tom", "nancy", "pablo"]

movieLine.push('oliver');
movieLine; // ["tom", "nancy", "pablo", "oliver"]

movieLine.push('eva');
movieLine; // ["tom", "nancy", "pablo", "oliver", "eva"]

movieLine.push('harry', 'hermione');
movieLine; // ["tom", "nancy", "pablo", "oliver", "eva", "harry", "hermione"]

🤛 pop() - remove from end

movieLine; // ["tom", "nancy", "pablo", "oliver", "eva", "harry", "hermione"]

movieLine.pop() // "hermione"
movieLine; // ["tom", "nancy", "pablo", "oliver", "eva", "harry"]


let person = movieLine.pop();

person; // "harry"
movieLine; // ["tom", "nancy", "pablo", "oliver", "eva"]

🏋️‍♂️ barbell example (stack & queue)

let barbell = [];

barbell.push(45);
barbell.push(45);
barbell.push(25);
barbell.push(10);
barbell.push(2.5);

barbell; // [45, 45, 25, 10, 2.5]

barbell.pop(); // 2.5
barbell.pop(); // 10
barbell.pop(); // 25
barbell.pop(); // 45
barbell.pop(); // 45

🤜 shift() - remove from start

movieLine; // ["tom", "nancy", "pablo", "oliver", "eva"]

movieLine.shift(); // "tom"
movieLine; // ["nancy", "pablo", "oliver", "eva"]

let nextPatron = movieLine.shift();
nextPatron; // "nancy"
movieLine; ["pablo", "oliver", "eva"]

movie.push('ryan');

movieLine.shift(); // "pablo"
movieLine.shift(); // "oliver"
movieLine.shift(); // "eva"
movieLine.shift(); // "ryan"

movieLine.shift(); // undefined

👉 unshift() - add to start

movieLine.push('jerry', 'deniz', 'kevin', 'carly');
movieLine; // ["jerry", "deniz", "kevin", "carly"]

movieLine.unshift('VIP');
movieLine; // ["VIP", "jerry", "deniz", "kevin", "carly"]

movieLine.shift(); // "VIP"
movieLine; // ["jerry", "deniz", "kevin", "carly"]
profile
👨🏻‍💻☕️ 🎹🎵 🐰🎶 🛫📷

0개의 댓글