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

浏览器兼容性

另见