美文网首页
js删除或添加元素:splice()

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

作者: wshining | 来源:发表于2017-05-24 23:50 被阅读0次

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);//[]

var array = ["one","two","three","four","five","six"];

console.log(array.splice(1,2));// ["two", "three"]

console.log(array);// ["one", "four", "five", "six"]

注: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();

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

数组

相关文章

网友评论

      本文标题:js删除或添加元素:splice()

      本文链接:https://www.haomeiwen.com/subject/mjkaxxtx.html