Array.prototype.push()

Baseline 已廣泛支援

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

Array 例項的 push() 方法將指定元素新增到陣列的末尾,並返回陣列的新長度。

試一試

const animals = ["pigs", "goats", "sheep"];

const count = animals.push("cows");
console.log(count);
// Expected output: 4
console.log(animals);
// Expected output: Array ["pigs", "goats", "sheep", "cows"]

animals.push("chickens", "cats", "dogs");
console.log(animals);
// Expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]

語法

js
push()
push(element1)
push(element1, element2)
push(element1, element2, /* …, */ elementN)

引數

element1, …, elementN

要新增到陣列末尾的一個或多個元素。

返回值

呼叫該方法的物件的新 length 屬性。

描述

push() 方法會將值追加到陣列中。

Array.prototype.unshift() 的行為與 push() 類似,但應用於陣列的開頭。

push() 方法是 修改原陣列的方法。它會更改 this 的長度和內容。如果你希望 this 的值保持不變,而是返回一個末尾追加了元素的新陣列,可以使用 arr.concat([element0, element1, /* ... ,*/ elementN])。請注意,元素被包裝在一個額外的陣列中——否則,如果元素本身就是一個數組,它會被展開而不是作為一個單獨的元素被推送,這是 concat() 的行為所致。

push() 方法是 通用的。它只期望 this 值具有 length 屬性和整數鍵屬性。儘管字串也具有類似陣列的特性,但此方法不適用於字串,因為字串是不可變的。

示例

向陣列新增元素

以下程式碼建立了包含兩個元素的 sports 陣列,然後向其追加了兩個元素。total 變數包含陣列的新長度。

js
const sports = ["soccer", "baseball"];
const total = sports.push("football", "swimming");

console.log(sports); // ['soccer', 'baseball', 'football', 'swimming']
console.log(total); // 4

合併兩個陣列

此示例使用 展開語法 將第二個陣列的所有元素推送到第一個陣列中。

js
const vegetables = ["parsnip", "potato"];
const moreVegs = ["celery", "beetroot"];

// Merge the second array into the first one
vegetables.push(...moreVegs);

console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot']

也可以使用 concat() 方法來合併兩個陣列。

在非陣列物件上呼叫 push()

push() 方法讀取 thislength 屬性。然後,它從 length 開始,使用傳遞給 push() 的引數為 this 的每個索引賦值。最後,它將 length 設定為之前的長度加上推送的元素數量。

js
const arrayLike = {
  length: 3,
  unrelated: "foo",
  2: 4,
};
Array.prototype.push.call(arrayLike, 1, 2);
console.log(arrayLike);
// { '2': 4, '3': 1, '4': 2, length: 5, unrelated: 'foo' }

const plainObj = {};
// There's no length property, so the length is 0
Array.prototype.push.call(plainObj, 1, 2);
console.log(plainObj);
// { '0': 1, '1': 2, length: 2 }

將物件用作類陣列

如上所述,push 刻意設計成通用的,我們可以利用這一點。Array.prototype.push 可以很好地作用於物件,如本示例所示。

請注意,我們沒有建立一個數組來儲存物件的集合。相反,我們將集合儲存在物件本身上,並對 Array.prototype.push 使用 call,以欺騙該方法,讓它認為我們正在處理一個數組——而且它確實有效,這得益於 JavaScript 允許我們以任何方式建立執行上下文的方式。

js
const obj = {
  length: 0,

  addElem(elem) {
    // obj.length is automatically incremented
    // every time an element is added.
    [].push.call(this, elem);
  },
};

// Let's add some empty objects just to illustrate.
obj.addElem({});
obj.addElem({});
console.log(obj.length); // 2

請注意,儘管 obj 不是一個數組,但 push 方法成功地增加了 objlength 屬性,就像我們處理實際陣列一樣。

規範

規範
ECMAScript® 2026 語言規範
# sec-array.prototype.push

瀏覽器相容性

另見