Javascript--Array數組的splice()方法之刪除、插入、替換__Java

來源:互聯網
上載者:User

Array數組的splice()方法,也是一個非常強大的方法,它的作用是:刪除、插入、替換

需要注意的是: splice()方法是直接修改原數組的


一、刪除的用法

文法: array.splice(starti,n);


starti 指的是從哪個位置開始(不包含starti)

n指的是需要刪除的個數

[html]  view plain  copy <script>       var array=[1,2,3,4,5];       array.splice(3,2);       console.log(array);   </script>  


結果: [1,2,3]


這裡有個小拓展:其實被刪除的元素可以用一個變數接收的,這個接收的變數可以作為拼接數組來使用

 
[html] view plain copy <script>       var array=[1,2,3,4,5];       var deletes =array.splice(3,2);       console.log(deletes);       console.log(array);   </script>   
結果: [4,5] [1,2,3] 
我們將刪除後的元素在拼接回原來的數組
 
[html] view plain copy <script>       var array=[1,2,3,4,5];       var deletes =array.splice(3,2);       console.log(deletes);       console.log(array);       array=array.concat(deletes);       console.log(array);   </script>   
結果: [4,5] [1,2,3] [1,2,3,4,5] 
二、插入的用法
 
文法:array.splice(starti,0,值1,值2...);
 
starti: 在哪個位置插入,原來starti位置的值向後順移
0:表示刪除0個元素,因為插入和替換都是由刪除功能拓展的。
值1,值2:需要插入的值
 
 
[html] view plain copy <script>       var array=[1,2,3,4,5];       array.splice(2,0,123,456);       console.log(array);   </script>   結果: [1,2,123,456,3,4,5] 
 
 
 
三、替換的用法
文法:array.splice(starti,n,值1,值2);
原理和插入的用法相同
實際是就是:在starti的位置刪除n個元素,然後在這個位置插入值1,值2,就可以起到替換
原來被刪除的值
 

[html]  view plain  copy <span style="font-size:24px;"><script>       var array=[1,2,3,4,5];       array.splice(2,2,123,456);       console.log(array);   </script></span>  

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.