js中的splice() 方法

splice() 方法会直接对数组进行修改方法会直接对数组进行修改

 

例子 1
创建一个新数组,并向其添加一个元素:

<script type="text/javascript">

var arr = new Array(6)
arr[0] = "George"
arr[1] = "John"
arr[2] = "Thomas"
arr[3] = "James"
arr[4] = "Adrew"
arr[5] = "Martin"

document.write(arr + "<br />")
arr.splice(2,0,"William")
document.write(arr + "<br />")

</script>输出:

George,John,Thomas,James,Adrew,Martin
George,John,William,Thomas,James,Adrew,Martin

 

 

例子 2

删除从 index 2 ("Thomas") 开始的三个元素,并添加一个新元素 ("William") 来替代被删除的元素:

<script type="text/javascript">

var arr = new Array(6)
arr[0] = "George"
arr[1] = "John"
arr[2] = "Thomas"
arr[3] = "James"
arr[4] = "Adrew"
arr[5] = "Martin"

document.write(arr + "<br />")
arr.splice(2,3,"William")
document.write(arr)

</script>输出:

George,John,Thomas,James,Adrew,MartinGeorge,John,William,Martin

 

你可能感兴趣的:(splice)