Javascript中用splice()来删除数组中的元素

本文详细介绍了 JavaScript 数组方法 splice() 的使用方法,包括如何通过该方法添加、替换及删除数组元素,并提供了具体的代码示例。
一、splice()的用法 
arrayObject.splice(index,howmany,element1,.....,elementX)

Parameter
参数 Description
描述
index Required. Specify where to add/remove elements. Must be a number
必选项。指定在哪个位置加入/删除元素,必须是数字
howmany Required Specify how many elements should be removed. Must be a number, but can be "0"
必选项。指定有多少元素应该被删除。必须是数字,可以是"0"
element1 Optional. Specify a new element to add to the array
可选。指定要加入到数组中的新元素
elementX Optional. Several elements can be added
可选。可以加入多个元素

Example
举例In this example we will create an array and add an element to it:
在这个举例中我们将建立一个数组并为它加入一个元素:

<script type="text/javascript">
var arr = new Array(5)
arr[0] = "Jani"
arr[1] = "Hege"
arr[2] = "Stale"
arr[3] = "Kai Jim"
arr[4] = "Borge"
document.write(arr + "<br />")
arr.splice(2,0,"Lene")
document.write(arr + "<br />")
</script>

The output of the code above will be:
输出结果为:

Jani,Hege,Stale,Kai Jim,Borge
Jani,Hege,Lene,Stale,Kai Jim,Borge


--------------------------------------------------------------------------------
Example
举例In this example we will remove the element at index 2 ("Stale"), and add a new element ("Tove") there instead:
这个举例中我们将删除数组中index值为2的元素("Stale"),并在这个位置加上新的元素("Tove"):

<script type="text/javascript">
var arr = new Array(5)
arr[0] = "Jani"
arr[1] = "Hege"
arr[2] = "Stale"
arr[3] = "Kai Jim"
arr[4] = "Borge"
document.write(arr + "<br />")
arr.splice(2,1,"Tove")
document.write(arr)
</script>

The output of the code above will be:
输出结果为:

Jani,Hege,Stale,Kai Jim,Borge
Jani,Hege,Tove,Kai Jim,Borge


--------------------------------------------------------------------------------
Example
举例In this example we will remove three elements starting at index 2 ("Stale"), and add a new element ("Tove") there instead:
在这个举例中我们将会从index值为2的位置删除三个元素("Stale"开始),并在这个位置加上一个新的元素("Tove"):

<script type="text/javascript">
var arr = new Array(5)
arr[0] = "Jani"
arr[1] = "Hege"
arr[2] = "Stale"
arr[3] = "Kai Jim"
arr[4] = "Borge"
document.write(arr + "<br />")
arr.splice(2,3,"Tove")
document.write(arr)
</script>

The output of the code above will be:
输出结果为:

Jani,Hege,Stale,Kai Jim,BorgeJani,Hege,Tove


二、删除数组的要素
如果是最后一个要素,直接 aobject.splice(aobject.length-1,1)
知道要素下标N aobject.splice(N,1)
知道要素内容,需要for循环获得的下标,再删除
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值