JavaScript 数组 splice()方法
JavaScript数组splice()方法用于向现有数组中添加/删除元素。它返回从数组中删除的元素。splice()方法还修改原始数组。
语法
splice()方法的语法如下所示:
array.splice(start,delete,element1,element2,?,elementn)
参数
start - 它代表从数组中开始提取元素的索引。
delete - 这是可选的。它表示要删除的元素数量。
element1,element2,…,elementn - 这是可选的。它表示要插入的元素。
返回值
一个包含被删除元素的新数组。
JavaScript 数组的 splice() 方法示例
在这里,我们将通过各种示例来理解 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("Updated array: "+arr+"<br>");
document.writeln("Removed element: "+result);
</script>
输出:
Updated array: Monday,Tuesday,Wednesday,Thursday,Friday
Removed element: Saturday,Sunday
示例3
让我们看一个示例,向现有的数组中添加两个元素同时移除一个元素。
<script>
var arr=["Monday","Tuesday","Sunday","Friday"];
var result=arr.splice(2,1,"Wednesday","Thursday");
document.writeln("Updated array: "+arr+"<br>");
document.writeln("Removed element: "+result);
</script>
输出结果:
Updated array: Monday,Tuesday,Wednesday,Thursday,Friday
Removed element: 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>
输出:
Updated array: Monday,Tuesday
Removed element: Saturday,Sunday,Thursday,Friday