Home > Article > Web Front-end > Detailed graphic explanation of three methods of adding elements to arrays in JavaScript
Arrays are an important part of JavaScript, so do you know how to add elements to JS arrays? This article will tell you how to add elements to JS arrays. It has certain reference value. Interested friends can take a look.
Method 1, unshift() method
The unshift method can add one or more elements to the beginning of the array, and then return the length of the new array, and all mainstream browsers All processors support the unshift method.
Syntax: array.unshift(item1,item2, ..., itemX)
Example: Click the button to add "dog" to the beginning of the array
The code is as follows :
Rendering:
##Method 2, push() method## The #push method can add one or more elements to the end of the array and then return the length of the new array, and all major browsers support the push() method.
Syntax: array.push(item1, item2, ..., itemX)
The code is as follows:
Method 3, splice() methodThe splice() method can insert, delete or replace elements into an array, and all major browsers support the splice method.
Syntax: array.splice(index,howmany,item1,...,itemX)
index indicates where to add or delete elements, howmany indicates how many elements should be deleted, item indicates to add to the new element of the array.
The code is as follows:
For more related tutorials, please visit
JavaScript video tutorialThe above is the detailed content of Detailed graphic explanation of three methods of adding elements to arrays in JavaScript. For more information, please follow other related articles on the PHP Chinese website!