JavaScript 中数组的 splice() 方法

splice( 开始的位置,要删除的个数 [,插入的项1 ] [,插入的项2 ][...] )

直接对原数组进行处理,返回一个数组,包含从原数组中删除的项

1、删除任意位置项 ------ 传入两个参数,第二个参数不为0;

2、从任意位置添加新项 ----- 传入三个及以上参数,第二个参数为0;

3、替换任意位置项 ----- 传入三个及以上参数,第二个参数不为0。

var colors = ["red", "green", "blue"];

var removed = colors.splice(0,1);              //删除第一项
alert(colors);        //green,blue
        
removed = colors.splice(1, 0, "yellow", "orange");  //从位置1开始插入两项
alert(colors);       //green,yellow,orange,blue

removed = colors.splice(1, 1, "red", "purple");    //将第二项替换为传入的两项
alert(colors);       //green,red,purple,orange,blue

如果只传入一个参数,表示数组从该位置开始,截取到数组末尾,返回截取的数组,原数组变为剩余的部分

var colors = ["red", "green", "blue","red", "green", "blue","red", "green", "blue"];
var newColors = colors.splice(4);
alert(newColors)        //["green", "blue", "red", "green", "blue"]
alert(colors)        //["red", "green", "blue", "red"]
对比用两个参数删除数组的做法
var colors = ["red", "green", "blue","red", "green", "blue","red", "green", "blue"];
var newColors = colors.splice(0,4)
alert(newColors)        //["red", "green", "blue", "red"]
alert(colors)        //["green", "blue", "red", "green", "blue"]
上面的例子说明,在使用splice截取数组的时候,传入的参数不同,要注意需要取返回值,还是取改变后的原数组。






  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值