使用Array类型的splice方法可以对数组元素进行插入、替换、删除。该方法讲直接影响当前的数组对象(与.slice(index1,index2)方法不同)并返回被删除的数组项。
参数:
index :数组中元素的起始下标。
count :需要要被删除或替换的元素个数。
elems :需要插入到数组中的项。
返回值 :返回从素组中被移除的项。
演示:
在本例中,我们将创建一个新数组,并向其添加一个元素:
输出:
George,John,Thomas,James,Adrew,MartinGeorge,John,William,Thomas,James,Adrew,Martin
在本例中我们将替换位于 index 2 的元素:
输出:
George,John,Thomas,James,Adrew,MartinGeorge,John,William,James,Adrew,Martin
在本例中我们将删除从 index 2 ("Thomas") 开始的三个元素,并添加一个新元素 ("William") 来替代被删除的元素:
输出:
George,John,Thomas,James,Adrew,MartinGeorge,John,William,Martin