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>