JS数组添加元素的三种方法
1、push() 方法可以向数组末尾添加一个或多个元素,并且返回新的长度
语法:arr.push(element1,element2,element3,····)
参数 | 概述 |
---|---|
element1 | 必写,添加到数组的第一个元素 |
element2 | 可写可不写,添加的第二个元素 |
element3 | 添加的第三个元素 |
以此类推,看需要添加元素的数量,并且它是按参数顺序排列元素,直接修改 arr,而不是创建一个新的数组。
var arr = new Array(3)
arr[0] = "xiao"
arr[1] = "fan"
arr[2] = "xiaofan"
console.log(arr);// ["xiao","fan","xiaofan"]
console.log(arr.push("C"));// 4
console.log(arr);// ["xiao","fan","xiaofan","C"]
console.log(arr.push("A","B"));// 6
console.log(arr);// ["xiao","fan","xiaofan","A","B","C"]
2.unshift() 方法是向数组前面添加一个或者多个元素,并且返回长度
语法:arr.unshift(element1,element2,·····)
把添加的新元素放在数组的最前面,以往的数组元素依次排在新元素的后面
参数 | 概述 |
---|---|
element1 | 向数组添加的第一个元素 |
element2 | 可写可不写,添加的第二个元素 |
······ | 添加的第n个元素 |
var arr = new Array(3)
arr[0] = "xiao"
arr[1] = "fan"
arr[2] = "xiaofan"
console.log(arr);// ["xiao","fan","xiaofan"]
console.log(arr.unshift("C"));// 4
console.log(arr);// ["C","xiao","fan","xiaofan"]
console.log(arr.unshift("A","B"));// 6
console.log(arr);// ["A","B","C","xiao","fan","xiaofan"]
3、splice() 方法向从数组中添加或者删除元素,然后返回被删除的元素。
语法:arr.splice(index,howmany,item1,…)
splice() 方法可删除从 index 处开始的零个或多个元素,并且用参数列表中声明的一个或多个值来替换那些被删除的元素。
如果从 arr中删除了元素,则返回的是含有被删除的元素的数组。
参数 | 概述 |
---|---|
index | 添加或删除的位置,用负数的话,可以从末尾算起 |
howmany | 删除的数量,如果设置为0则不删除元素 |
item1,······ | 添加的第n个元素 |
var arr = ["A","xiao","fan","xiaofan"];
console.log(arr.splice(1,0,"B","C"));// []
console.log(arr);// ["A","B","C","xiao","fan","xiaofan"]
console.log(arr.splice(1,2));// ["B","C"]
console.log(arr);// ["A","xiao","fan","xiaofan"]
console.log(arr.splice(1,1,"D"));// ["xiao"]
console.log(arr);// ["A","D","fan","xiaofan"]