js中splice表示从一个数组中移除一个或多个元素,它可以用于插入、删除或替换数组的元素,如果必要,在所移除元素的位置上插入新元素,返回所移除的元素。splice方法会改变原始数组。
1. 1 splice实例
var lang = ["php","java","javascript"]; //删除 var removed = lang.splice(1,1); alert(lang); //php,javascript alert(removed); //java ,返回删除的项 //插入 var insert = lang.splice(0,0,"asp"); //从第0个位置开始插入 alert(insert); //返回空数组 alert(lang); //asp,php,javascript //替换 var replace = lang.splice(1,1,"c#","ruby"); //删除一项,插入两项 alert(lang); //asp,c#,ruby,javascript alert(replace); //php,返回删除的项
1.2 splice实例(插入)
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 />")
//输出:
//George,John,Thomas,James,Adrew,Martin
//George,John,William,Thomas,James,Adrew,Martin
1.3 splice实例(替换)
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,1,"William") document.write(arr) //输出: //George,John,Thomas,James,Adrew,Martin //George,John,William,James,Adrew,Martin
1.4 splice实例(替换)
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) //输出: //George,John,Thomas,James,Adrew,Martin //George,John,William,Martin