试一试
const array = [1, 2, 3];
console.log(array.unshift(4, 5));
// Expected output: 5
console.log(array);
// Expected output: Array [4, 5, 1, 2, 3]
语法
js
unshift()
unshift(element1)
unshift(element1, element2)
unshift(element1, element2, /* …, */ elementN)
参数
element1, …,elementN-
要添加到
arr开头的元素。
返回值
调用该方法的对象的新的 length 属性。
描述
unshift() 方法将给定的值插入到类数组对象的开头。
Array.prototype.push() 的行为与 unshift() 类似,但应用于数组的末尾。
请注意,如果作为参数传递了多个元素,它们将作为一个整体插入到对象的前面,顺序与作为参数传递时的顺序完全相同。因此,一次调用 unshift() 并带 n 个参数,或者(例如通过循环)调用 n 次 unshift() 并每次带1个参数,结果是不同的。
查看示例
js
let arr = [4, 5, 6];
arr.unshift(1, 2, 3);
console.log(arr);
// [1, 2, 3, 4, 5, 6]
arr = [4, 5, 6]; // resetting the array
arr.unshift(1);
arr.unshift(2);
arr.unshift(3);
console.log(arr);
// [3, 2, 1, 4, 5, 6]
unshift() 方法是 通用的。它只期望 this 值具有 length 属性和整数键属性。尽管字符串也类似于数组,但此方法不适用于字符串,因为字符串是不可变的。
示例
使用 unshift()
js
const arr = [1, 2];
arr.unshift(0); // result of the call is 3, which is the new array length
// arr is [0, 1, 2]
arr.unshift(-2, -1); // the new array length is 5
// arr is [-2, -1, 0, 1, 2]
arr.unshift([-4, -3]); // the new array length is 6
// arr is [[-4, -3], -2, -1, 0, 1, 2]
arr.unshift([-7, -6], [-5]); // the new array length is 8
// arr is [ [-7, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ]
在非数组对象上调用 unshift()
unshift() 方法读取 this 的 length 属性。它将范围 0 到 length - 1 中的所有索引向右移动参数的数量(将它们的值增加这个数量)。然后,它使用传递给 unshift() 的参数设置从 0 开始的每个索引。最后,它将 length 设置为之前的长度加上添加的元素数量。
js
const arrayLike = {
length: 3,
unrelated: "foo",
2: 4,
};
Array.prototype.unshift.call(arrayLike, 1, 2);
console.log(arrayLike);
// { '0': 1, '1': 2, '4': 4, length: 5, unrelated: 'foo' }
const plainObj = {};
// There's no length property, so the length is 0
Array.prototype.unshift.call(plainObj, 1, 2);
console.log(plainObj);
// { '0': 1, '1': 2, length: 2 }
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-array.prototype.unshift |
浏览器兼容性
加载中…