Array.prototype.push()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

Array 实例的 push() 方法将指定元素添加到数组末尾并返回数组的新长度。

¥The push() method of Array instances adds the specified elements to the end of an array and returns the new length of the array.

Try it

语法

¥Syntax

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

参数

¥Parameters

element1, …, elementN

要添加到数组末尾的元素。

返回值

¥Return value

调用该方法的对象的新 length 属性。

¥The new length property of the object upon which the method was called.

描述

¥Description

push() 方法将值附加到数组中。

¥The push() method appends values to an array.

Array.prototype.unshift()push() 具有类似的行为,但应用于数组的开头。

¥Array.prototype.unshift() has similar behavior to push(), but applied to the start of an array.

push() 方法是 变异法 方法。它改变了 this 的长度和内容。如果你希望 this 的值相同,但返回一个新数组,并将元素追加到末尾,则可以使用 arr.concat([element0, element1, /* ... ,*/ elementN]) 代替。请注意,元素被封装在一个额外的数组中 - 否则,如果元素本身是一个数组,则由于 concat() 的行为,它将被展开而不是作为单个元素推送。

¥The push() method is a mutating method. It changes the length and the content of this. In case you want the value of this to be the same, but return a new array with elements appended to the end, you can use arr.concat([element0, element1, /* ... ,*/ elementN]) instead. Notice that the elements are wrapped in an extra array — otherwise, if the element is an array itself, it would be spread instead of pushed as a single element due to the behavior of concat().

push() 方法是 generic。它只期望 this 值具有 length 属性和整数键控属性。虽然字符串也是类似数组的,但此方法不适合应用于它们,因为字符串是不可变的。

¥The push() method is generic. It only expects the this value to have a length property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.

示例

¥Examples

向数组添加元素

¥Adding elements to an array

以下代码创建包含两个元素的 sports 数组,然后向其中追加两个元素。total 变量包含数组的新长度。

¥The following code creates the sports array containing two elements, then appends two elements to it. The total variable contains the new length of the array.

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

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

合并两个数组

¥Merging two arrays

此示例使用 spread syntax 将第二个数组中的所有元素推入第一个数组中。

¥This example uses spread syntax to push all elements from a second array into the first one.

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() 方法来完成。

¥Merging two arrays can also be done with the concat() method.

对非数组对象调用 push()

¥Calling push() on non-array objects

push() 方法读取 thislength 属性。然后,它设置从 length 开始的 this 的每个索引,并将参数传递给 push()。最后,它将 length 设置为先前的长度加上推送的元素数量。

¥The push() method reads the length property of this. It then sets each index of this starting at length with the arguments passed to push(). Finally, it sets the length to the previous length plus the number of pushed elements.

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 }

以类似数组的方式使用对象

¥Using an object in an array-like fashion

如上所述,push 是故意通用的,我们可以利用它来发挥我们的优势。Array.prototype.push 可以很好地处理对象,如本例所示。

¥As mentioned above, push is intentionally generic, and we can use that to our advantage. Array.prototype.push can work on an object just fine, as this example shows.

请注意,我们不会创建数组来存储对象集合。相反,我们将集合存储在对象本身上,并在 Array.prototype.push 上使用 call 来欺骗该方法,让该方法认为我们正在处理一个数组 - 而且它确实有效,这要归功于 JavaScript 允许我们以任何我们想要的方式建立执行上下文。 。

¥Note that we don't create an array to store a collection of objects. Instead, we store the collection on the object itself and use call on Array.prototype.push to trick the method into thinking we are dealing with an array—and it just works, thanks to the way JavaScript allows us to establish the execution context in any way we want.

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 属性,就像我们处理实际数组一样。

¥Note that although obj is not an array, the method push successfully incremented obj's length property just like if we were dealing with an actual array.

规范

Specification
ECMAScript Language Specification
# sec-array.prototype.push

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看