Home >Web Front-end >JS Tutorial >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 :
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <button onclick="myFunction()">点我</button> </body> <script type="text/javascript"> function myFunction(){ var animal = ["cat", "elephant", "tiger","rabbit"]; var animal1= animal.unshift("dog"); document.write("数组长度:"+ animal1+"新数组:"+animal) } </script> </html>
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:
<script type="text/javascript"> function myFunction(){ var animal = ["cat", "elephant", "tiger","rabbit"]; var animal1= animal.push("dog"); document.write("数组长度:"+ animal1+"新数组:"+animal) } </script>Method 3, splice() method
The 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:
<script type="text/javascript"> function myFunction(){ var animal = ["cat", "elephant", "tiger","rabbit"]; var animal1= animal.splice(0,0,"dog"); document.write("新数组:"+animal) } </script>
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!