Array.prototype.unshift()

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

unshift() 方法用於 Array 例項,將指定元素新增到陣列的開頭,並返回陣列的新長度。

試一試

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() 方法讀取 thislength 屬性。它將範圍 0length - 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

瀏覽器相容性

另見