<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>删除数组元素的粗略方法</title>
<script src="../unitl/test.js"></script>
<style>
#results li.pass {color:green;}
#results li.fail {color:red;}
</style>
</head>
<body>
<ul id="results"></ul>
</body>
<script>
const ninjas = ["Yagyu","Kuma","Hattori","Fuma"];
//使用内置的splice方法从索引1开始,删除1个元素。
var removedItems = ninjas.splice(1,1);
assert(removedItems.length === 1,"One item was removed");
assert(removedItems[0] === "Kuma");
assert(ninjas.length ===3,"There are now threee items in the array");
assert(ninjas[1] === "Hattori","Hattori is now in the second place");
assert(ninjas[2]==="Fuma","Add Fuma is in the third place");
removedItems = ninjas.splice(1,2,"Mochizuki","Yoshi","Momochi");
assert(removedItems.length ===2,"Now ,we've removed two items");
assert(removedItems[0] === "Hattori","Hattori was removed");
assert(removedItems[1] === "Fuma","Fuma was removed");
assert(ninjas.length === 4, "We've inserted some new items");
assert(ninjas[0] === "Yagyu","Yagyu is still here");
assert(ninjas[1] === "Mochizuki","Mochizuki also" );
assert(ninjas[2] === "Yoshi","Yoshi also");
assert(ninjas[3] === "Momochi","and Momochi");
</script>
</html>
本例子中引入的js: test.js
首先创建一个具有4个元素的数组:
var ninjas = ["Yagyu","Kuma","Hattori","Fuma"];
然后调用内置的splice方法
var removedItems = ninjas.splice(1,1); //ninjas:["Yogyu","Hattori","Fuma"]; //removedItems:["Kuma"].
在本例中,splice具有两个参数:起始索引和需要移除的个数(这个参数如果不传,会一直删除元素知道数组末尾的元素)。在本例中,索引是1的元素是删除,后续元素自动相应移动。
同时,splice方法返回被移除的元素数组。在本例子,返回的数组只有一个元素:Kuma。
使用splice方法,也可以是现在数组任意位置插入元素。例如,看看如下代码:
removedItems = ninjas.splice(1,2,"Mochizuki","Yoshi","Momochi");
//ninjas:["Yagyu","Mochizuki","Yoshi","Momochi"]
从索引1开始,首先移除2个元素,然后添加3个元素:"Mochizuki","Yoshi"和"Momochi"。