[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/push [Back]  [Original]

Array.prototype.push() - JavaScript | MDN

MDN Web Docs

View in English Always switch to English

Array.prototype.push()

Baseline Widely available

This feature is well established and works across many devices and browser versions. Its been available across browsers since 20157.

push()

In this article

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
arr.push(element1[, ...[, elementN]])

elementN

length

push

push call() apply() push length length 0 length length

array-likeimmutable

sports total

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

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

apply()

moreVegs apply()

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

// Merge the second array into the first one
// Equivalent to vegetables.push('celery', 'beetroot');
Array.prototype.push.apply(vegetables, moreVegs);

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

array-like

push Array.prototype.push collection call Array.prototype.push JavaScript

js
var obj = {
  length: 0,

  addElem: function 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 obj length

Specification
ECMAScript 2027 LanguageSpecification
# sec-array.prototype.push


Web Proxy Viewer  |  New URL  |  Original Page