📅  最后修改于: 2023-12-03 15:01:38.431000             🧑  作者: Mango
JavaScript push()
is a built-in method that allows us to add one or more elements to the end of an array and returns the new length of the array. In this article, we’ll explore the push()
method in detail.
The syntax for the push()
method is as follows:
array.push(element1, element2, ... , elementN)
where array
is the array on which the push()
method is called, and element1
, element2
, ..., elementN
are the elements that are to be added to the end of the array.
let fruits = ['apple', 'banana'];
console.log(fruits.push('orange')); // 3
console.log(fruits); // ["apple", "banana", "orange"]
console.log(fruits.push('grape', 'kiwi')); // 5
console.log(fruits); // ["apple", "banana", "orange", "grape", "kiwi"]
In the above example, we have an array fruits
containing two elements. We use the push()
method to add an element 'orange'
to the end of the fruits
array and log the new length of the array. Similarly, we add two more elements 'grape'
and 'kiwi'
to the fruits
array using the push()
method and log the updated fruits
array.
JavaScript push()
method is useful when we want to add elements to the end of an array. It modifies the original array and returns the new length of the array.