📅  最后修改于: 2023-12-03 15:38:17.675000             🧑  作者: Mango
在javascript中,我们经常需动态地向数组中添加数据。以以下代码为例:
let fruits = ["apple", "banana", "orange"];
现在我们需要向fruits数组中添加一个新的水果,比如grape。如何实现呢?
push方法是向数组中添加一个元素,将其放在数组末尾。
fruits.push("grape");
console.log(fruits); // ["apple", "banana", "orange", "grape"]
concat方法返回一个新数组,包含原数组加上新元素,不会改变原数组。
let newFruits = fruits.concat("grape");
console.log(newFruits); // ["apple", "banana", "orange", "grape"]
console.log(fruits); // ["apple", "banana", "orange"]
splice方法可实现向数组中指定位置插入数据。
let index = 1;
let insertFruit = "grape";
fruits.splice(index, 0, insertFruit);
console.log(fruits); // ["apple", "grape", "banana", "orange"]
这里的意思是,将新的水果grape插入到数组的第2个位置(数组下标从0开始),插入前不删除原数组中的任何元素。
还可以使用splice方法实现向数组中删除元素或替换元素。
以上是javascript中动态向数组中添加数据的常用方法,可以根据自己的需求选择使用。