JavaScript unshift 方法
最后修改于 2025 年 4 月 4 日
在本文中,我们将展示如何使用 JavaScript 中的 unshift 方法向数组的开头添加元素。
数组 unshift 操作
unshift 方法将一个或多个元素添加到数组的开头,并返回数组的新长度。 与 concat 不同,unshift 直接修改原始数组。
当您需要将元素添加到现有数组的前面时,此方法非常有用。 unshift 方法会更改数组的长度,并将所有现有元素移动到更高的索引,以便为新元素腾出空间。
unshift 方法可以接受多个参数。 每个参数都成为数组开头的的新元素。 这些元素按照它们提供给方法时的顺序添加。
基本的 unshift 示例
以下示例演示了 unshift 方法的基本用法。
main.js
const fruits = ['banana', 'apple'];
const newLength = fruits.unshift('orange');
console.log(fruits); // Modified original array
console.log(newLength); // New array length
我们创建一个数组,并向其开头添加一个新元素。 原始数组被修改。 该方法返回数组的新长度。
$ node main.js [ 'orange', 'banana', 'apple' ] 3
unshift 多个元素
unshift 方法可以一次添加多个元素。
main.js
const numbers = [3, 4]; const newLength = numbers.unshift(1, 2); console.log(numbers); console.log(newLength);
我们将两个元素添加到数组的开头。 这些元素按照指定的顺序添加。 该方法返回更新后的数组长度。
$ node main.js [ 1, 2, 3, 4 ] 4
unshift 不同的数据类型
unshift() 方法可以处理不同数据类型的元素。
main.js
const mixed = [true, {name: 'John'}];
mixed.unshift(42, 'hello', [1, 2]);
console.log(mixed);
我们将一个数字、一个字符串和一个数组添加到包含布尔值和一个对象的数组的开头。 JavaScript 数组可以包含混合数据类型。
$ node main.js
[ 42, 'hello', [ 1, 2 ], true, { name: 'John' } ]
向空数组 unshift
unshift 方法适用于空数组。
main.js
const empty = [];
const newLength = empty.unshift('first', 'second');
console.log(empty);
console.log(newLength);
当向空数组 unshift 时,这些元素将成为数组的内容。 该方法返回添加的元素数量,作为新的数组长度。
$ node main.js [ 'first', 'second' ] 2
性能注意事项
unshift 方法具有 O(n) 的时间复杂度,因为它必须移动所有现有元素。
main.js
const bigArray = new Array(1000000).fill(0);
console.time('unshift');
bigArray.unshift(1);
console.timeEnd('unshift');
此示例演示了向大型数组 unshift 的性能影响。 由于元素移动,该操作会随着数组大小的增加而变慢。
$ node main.js unshift: 5.234ms
来源
在本文中,我们演示了如何使用 unshift() 方法在 JavaScript 中向数组的开头添加元素。
作者
列出 所有 JS 数组函数。