JavaScript array.splice()
方法用于在现有数组中添加/删除元素。它返回从数组中删除的元素。 splice() 方法也会修改原始数组。
语法
splice() 方法由以下语法表示:
array.splice(start,delete,element1,element2,?,elementn)
参数
start - 它表示方法开始提取元素的索引位置。
delete- 可选。表示要移除的元素个数。
element1,element2,...,elementn - 可选。它表示要插入的元素。
返回
一个包含已移除元素的新数组。
方法示例
这里,我们将通过各种例子来了解splice()方法。
示例1
让我们看一个在现有数组中添加一个元素而不删除其他元素的示例。
<script>
var arr=["Monday","Tuesday","Thursday","Friday"];
var result=arr.splice(2,0,"Wednesday")
document.writeln(arr);
</script>
输出:
Monday,Tuesday,Wednesday,Thursday,Friday
示例2
让我们看一个例子,在现有数组中添加一个元素,同时删除其他元素。
<script>
var arr=["Monday","Tuesday","Saturday","Sunday","Thursday","Friday"];
var result=arr.splice(2,2,"Wednesday")
document.writeln("更新数组: "+arr+"<br>");
document.writeln("移除元素: "+result);
</script>
输出:
更新数组: Monday,Tuesday,Wednesday,Thursday,Friday
移除元素: Saturday,Sunday
移除元素: Saturday,Sunday
示例3
让我们看一个例子,在现有数组中添加两个元素,同时删除一个元素。
<script>
var arr=["Monday","Tuesday","Sunday","Friday"];
var result=arr.splice(2,1,"Wednesday","Thursday");
document.writeln("更新数组: "+arr+"<br>");
document.writeln("移除元素: "+result);
</script>
输出:
更新数组: Monday,Tuesday,Wednesday,Thursday,Friday
移除元素: Sunday
移除元素: Sunday
示例4
让我们看一个从现有数组中删除元素的示例。
<script>
var arr=["Monday","Tuesday","Saturday","Sunday","Thursday","Friday"];
var result=arr.splice(2);
document.writeln("Updated array: "+arr+"<br>");
document.writeln("Removed element: "+result);
</script>
输出:
更新数组: Monday,Tuesday
移除元素: Saturday,Sunday,Thursday,Friday
移除元素: Saturday,Sunday,Thursday,Friday