首页 前端知识 js中splice()方法

js中splice()方法

2024-11-04 10:11:08 前端知识 前端哥 228 114 我要收藏

        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

 

 

转载请注明出处或者链接地址:https://www.qianduange.cn//article/19925.html
标签
评论
发布的文章

JQuery中的load()、$

2024-05-10 08:05:15

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!