js中push(),pop(),unshift(),shift()的用法小結

來源:互聯網
上載者:User

標籤:pop   undefined   asc   java   fine   數組   頭部   bsp   span   

1、push()、pop()和unshift()、shift()

  這兩組同為對數組的操作,並且會改變數組的本身的長度及內容。

  不同的是 push()、pop() 是從數組的尾部進行增減,unshift()、shift() 是從數組的頭部進行增減。

 var arr = [1, 2];

2、push()和unshift()

  向數組的 尾部/頭部 添加若干元素,並返回 數組的 新長度;

  arr.push(3,4);         //返回 arr 的新長度 4

  arr ;                        // arr = [1,2,3,4];

  arr.unshift(0,0.5);    // 返回 arr 的新長度 6

  arr ;                       // arr = [0,0.5,1,2,3,4];

3、pop()和shift()

  從數組的 尾部/頭部 刪除1個元素(刪且只刪除1個),並返回 被刪除的元素;空數組是繼續刪除,不報錯,但返回undefined;

  arr.pop();      //返回 4;

  arr ;          // arr = [0,0.5,1,2,3];

  arr.pop();      //返回 3;

  arr ;         // arr = [0,0.5,1,2];

  arr.shift();      // 返回 0 ;

  arr ;        // arr = [0.5,1,2]

  PS: pop()和shift() 不接受傳參,即使傳了參數也沒什麼卵用~~;

  arr.pop(3) ;           // 返回 2;永遠返回最後一個;

  arr ;        // arr = [0.5,1];

  arr.shift(1);    // 返回 0.5; 永遠返回第一個;

  arr ;        // arr = [1];

  arr.pop() ;     // 返回 1;

  arr ;        // arr = [];

  arr.shift()     // 返回 undefined;

  arr ;        // arr = [];

js中push(),pop(),unshift(),shift()的用法小結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.