📅  最后修改于: 2023-12-03 15:10:22.409000             🧑  作者: Mango
在 JavaScript 中,当需要向数组添加新元素时,有几种方法可以使用。一种方法是使用 push()
函数,该函数将新元素添加到数组的末尾。另一种方法是使用 unshift()
函数,该函数将新元素添加到数组的开头。
push()
函数只接收一个参数,即要添加到数组的新元素。该函数会将新元素添加到数组末尾,并返回更新后的数组长度。
const fruits = ['apple', 'banana'];
const newLength = fruits.push('orange');
console.log(fruits); // ['apple', 'banana', 'orange']
console.log(newLength); // 3
unshift()
函数也只接收一个参数,即要添加到数组的新元素。该函数会将新元素添加到数组开头,并返回更新后的数组长度。
const fruits = ['apple', 'banana'];
const newLength = fruits.unshift('orange');
console.log(fruits); // ['orange', 'apple', 'banana']
console.log(newLength); // 3
如果要向数组添加多个元素,可以使用 push()
或 unshift()
函数的扩展语法(spread syntax)。
const fruits = ['apple', 'banana'];
fruits.push(...['orange', 'grape']);
console.log(fruits); // ['apple', 'banana', 'orange', 'grape']
const fruits = ['apple', 'banana'];
fruits.unshift(...['orange', 'grape']);
console.log(fruits); // ['orange', 'grape', 'apple', 'banana']
以上是向数组添加元素的方法。使用这些函数可以轻松地操作数组,以便实现所需的功能。