扫码一下
查看教程更方便
splice()方法更改数组的内容,在删除旧元素的同时添加新元素。
注意:这种方法会改变原始数组。
语法如下
array.splice(index, howMany, [element1][, ..., elementN]);
根据传递的参数返回提取的数组。
所有主流浏览器都支持 splice() 方法。
<html>
<head>
<title>JavaScript Array splice Method</title>
</head>
<body>
<script type = "text/javascript">
var arr = ["orange", "mango", "banana", "sugar", "tea"];
var removed = arr.splice(2, 0, "water");
document.write("After adding 1: " + arr );
document.write("<br />removed is: " + removed);
removed = arr.splice(3, 1);
document.write("<br />After adding 1: " + arr );
document.write("<br />removed is: " + removed);
</script>
</body>
</html>
输出结果
After adding 1: orange,mango,water,banana,sugar,tea
removed is:
After adding 1: orange,mango,water,sugar,tea
removed is: banana