当前位置: 首页 > 网络学院 > 客户端脚本教程 > JavaScript > JavaScript splice()方法

JavaScript
JS 介绍
JS 怎样使用
JS 在哪使用
JS 变量
JS If...Else
JS Switch
JS 操作符
JS Popup Boxes
JS 函数
JS For 循环
JS While 循环
JS Break 循环
JS For...In
JS 事件
JS Try...Catch
JS Throw
JS onerror
JS 特殊字符
JS Guidelines
JS 对象介绍

JavaScript splice()方法


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-03-04   浏览: 353 ::
收藏到网摘: n/a

Definition and Usage
一定与用法

The splice() method is used to remove and add new elements to an array.
splice()可向数组删除并加入新的元素。

Syntax
语法

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,Borge
Jani,Hege,Tove


Try-It-Yourself Demos
尝试与演示

splice()
How to use splice() to change an array.
怎样使用splice()来改变数组

评论 (0) All

登陆 | 还没注册?