[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/zh-CN/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()

20157

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(element0)
push(element0, element1)
push(element0, element1, /*  ,*/ elementN)

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"];

// 
vegetables.push(...moreVegs);

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

concat()

push()

push() this length this length push() 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 = {};
//  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 
    [].push.call(this, elem);
  },
};

// 
obj.addElem({});
obj.addElem({});
console.log(obj.length); // 2

obj push obj length

ECMAScript 2027 LanguageSpecification
# sec-array.prototype.push


Web Proxy Viewer  |  New URL  |  Original Page