js删除或添加元素:splice()

splice()

在MDN上的解释时该方法通过删除已存在的元素或添加新的元素来改变数组的内容,操作之后原数组会发生改变,splice()返回一个有删除元素组成的数组;

Syntax:

array.splice(start);

array.splice(start,deleteCount);

array.splice(start,deleteCount,item1,item2,item3);

 start:数组从start索引值开始删除或添加元素,start可以是0;当start>array.length,在MDN上说原数组的长度将设置成start,但是经过测试原数组的长度并没有改变;当start<0,原数组将从数组的最后开始删除|start|个数。

var array1 = ["one","two","three","four","five","six"];
console.log(array.splice(0));//["one", "two", "three", "four", "five", "six"]
console.log(array);//[]
var array1 = ["one","two","three","four","five","six"];
console.log(array.splice(3));//["four", "five", "six"]
console.log(array);//["one", "two", "three"]
var array2 = ["one","two","three","four","five","six"];
console.log(array.splice(8));//[]
console.log(array);//["one","two","three","four","five","six"]
var array3 = ["one","two","three","four","five","six"];
console.log(array.splice(-1));//["six"]
console.log(array);//["one", "two", "three", "four", "five"]
var array4 = ["one","two","three","four","five","six"];
console.log(array.splice(-8));//["one", "two", "three", "four", "five", "six"]
console.log(array);//[]

 

注:splice删除功能是对于原来的数组进行删除,执行splice()方法之后原数组内容发生改变;

deleteCount:整数、非负数,表明原数组需要删除元素的个数,当deleteCount=0,不删除元素;

点deleteCount>0时,原数组将从start索引值开始删除start个元素;当deleteCount参数被省略时,元素将从start索引值开始删除到最后;

var array = ["one","two","three","four","five","six"];
console.log(array.splice(1,2));// ["two", "three"]
console.log(array);// ["one", "four", "five", "six"]

item1,item2,item3...:添加到元素的元素,这些元素从start索引值开始添加,当这些元素被省略时,原数组只有删除功能没有添加功能;

var array1 = ["one","two","three","four","five","six"];
array.splice(1,2,"seven","eight");
console.log(array); //["one", "seven", "eight", "four", "five", "six"]
var array2= ["one","two","three","four","five","six"];
array.splice(1,0,"seven","eight");
console.log(array);  //["one", "seven", "eight", "two", "three", "four", "five", "six"]
var array = ["one","two","three","four","five","six"];
array.splice(1,4,"seven","eight");
console.log(array);//["one", "seven", "eight", "six"]

注:在数组可能要用到一些功能

1、删除索引值的数组元素,array.splice(start,1);

2、从索引值开始删除数组的n个元素,array.splice(start,n);

3、从索引值开始删除删除数组的元素到末尾,相当于保留索引值前面的数组元素,array.splice(start);

4、改变索引值数组元素的值:array.splice(start,1,item);

5、从索引值开始改变数组中的n个元素:array.splice(start,n,item1,item2,item3...);

6、从索引值开始向数组中天津n个元素:array.splice(start,0,item1,item2,item3...);

7、从数组的末尾开始删除一个元素或多个元素,array.splice(-count);

8、删除数组的最后一个元素,array.pop();

9、删除数组中第一个元素,array.shift();

以上删除方法返回的都是被删除元素的数组

 

转载于:https://my.oschina.net/u/1778998/blog/908500

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值