The role and difference of pop push unshift shift in vernacular JS

The function and difference of the array method pop push unshift shift in vernacular JS, through this article, you can probably know the basic use and general difference of these four array methods.

  First of all, these four methods modify the array directly , keep that in mind first.

  We first divide pop push unshift shift into two groups, push and unshift , which are understood as pushing elements into the array. A group of pop and shift is understood as pushing out the existing elements in the array.

  push: Adds an element to the end of the array and returns the length of the original length+1.

var arr = [ 1 , 2 , 3 ];
console.log(arr.push(4));//4
console.log(arr);//[1,2,3,4]

  unshift : Add an element to the head of the array and return the length of the original length+1.

var arr = [ 1 , 2 , 3 ];
console.log(arr.unshift(4));//4
console.log(arr);//[4,1,2,3]

  pop: delete the first element at the end of the array and return this element.

var arr = [ 1 , 2 , 3 ];
console.log(arr.pop());//3
console.log(arr);//[1,2]

  shift : removes the first element at the head of the array and returns this element.

var arr = [ 1 , 2 , 3 ];
console.log(arr.shift());//1
console.log(arr);//[2,3]

Summarize:

  1. These four methods will directly modify the original array

  2. Push and unshift add elements to the tail and head, respectively, and pop and shift delete elements to the tail and head, respectively.

  3. Push and unshift return the modified array length, and pop and shift return the deleted element.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324728829&siteId=291194637