Comparison of push(), pop(), unshift, shift() four array methods

Comparison of push(), pop(), unshift, shift() four array methods

 1. The push() method adds one or more array elements to the end of the array. Push means

Note: The result returned after push is the length of the new array

  var arr = [1, 2];
      
       //(3)push完毕后 返回的结果是新数组的长度
        console.log(arr.push(3));//3  新数组长度为3
        console.log(arr);// [1, 2, 3] 新数组为[1, 2, 3] 



2.unshift adds one or more array elements at the beginning of the array


      arr.unshift('red', '饿死了');
        console.log(arr.unshift('red', '饿死了'))    //5
        console.log(arr);;     //["red", "饿死了", 1, 2, 3]

(1) push, unshift is to add new elements to the array
(2) push(), the unshift parameter can directly write the array elements
(3) the original array will also change
3.pop() delete the last element in the array
   

    console.log(arr.pop());  //3   
        console.log(arr);   //["red", "饿死了", 1, 2]
        //pop()删除数组中最后一个元素
        //pop()没有参数
        //pop完毕后返回的结果是 删除的那个元素


4.shift() deletes the first element in the array and the result returned after shift is the deleted element shift() has no parameters

        console.log(arr.shift()); //red
        console.log(arr); //["饿死了", 1, 2]
 
        
     

 

Guess you like

Origin blog.csdn.net/are_gh/article/details/111184479