push() 方法可向数组的末尾添加一个或多个元素,并返回新的长度
示例:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
console.log(fruits);
//["Banana", "Orange", "Apple", "Mango","Kiwi"];
splice() 方法向/从数组中添加/删除项目,然后返回被删除的项目
示例:
//删除起始下标为1,长度为1的一个值(len设置1,如果为0,则数组不变)
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(1,1);
console.log(fruits);
//["Banana", "Apple", "Mango"];
//删除起始下标为1,长度为2的一个值(len设置2)
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(1,2);
console.log(fruits);
//["Banana", "Mango"];
//替换起始下标为1,长度为1的一个值为‘ttt’,len设置的1
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(1,1,'ttt');
console.log(fruits);
//["Banana", 'ttt',"Apple", "Mango"];
//替换起始下标为1,长度为2的两个值为‘ttt’,len设置的1
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(1,2,'ttt');
console.log(fruits);
//["Banana", 'ttt', "Mango"];
//在下标为1处添加一项’ttt’
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(1,0,'ttt');
console.log(fruits);
//["Banana", 'ttt', "Orange", "Apple", "Mango"];
向数组中间添加元素
var items = ["1", "2", "3", "4"];
items.splice(items.length / 2, 0, "hello");
console.log(items);
// ["1", "2", "hello", "3", "4"]