JavaScript的数组中添加元素的方法小结

时间:2022-06-06 04:18:25
1、在数组的开头添加新元素 - unshift()
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon","Pineapple");
Result:Lemon,Pineapple,Banana,Orange,Apple,Mango
2、在数组的第2位置添加一个元素 - splice()
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2,0,"Lemon","Kiwi");
Result:Banana,Orange,Lemon,Kiwi,Apple,Mango
3、数组的末尾添加新的元素 - push()
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi")
Result:Banana,Orange,Apple,Mango,Kiwi