본문 바로가기

Programming diary

33. February 26, 2021

.shift()

pop() always removes the last element of an array. What if you want to remove the first?

That's where .shift() comes in. It works just like .pop(), except it removes the first element instead of the last.

 

Example

var ourArray = ["Stimpson", "J", ["cat"]]; 
var removedFromOurArray = ourArray.shift(); 
// removedFromOurArray now equals "Stimpson" and ourArray now equals ["J", ["cat"]]

 

.unshift() 

Not only can you shift elements off of the beginning of an array, you can also unshift elements to the beginning of an array i.e. add elements in front of the array.

.unshift() works exactly like .push(), but instead of adding the element at the end of the array, unshift() adds the element at the beginning of the array.

 

Example

var ourArray = ["Stimpson", "J", "cat"]; 
ourArray.shift(); // ourArray now equals ["J", "cat"] ourArray.unshift("Happy"); 
// ourArray now equals ["Happy", "J", "cat"]

'Programming diary' 카테고리의 다른 글

35. July 4, 2021  (0) 2021.07.04
34. March 29, 2021  (0) 2021.03.29
32. February 25, 2021  (0) 2021.02.25
32. February 22, 2021  (0) 2021.02.22
31. January 11, 2021  (0) 2021.01.11