This article introduces how to add new elements to JSarrays, using different methods to add elements to JS arrays. Arrays are very commonly used in JSdata One of the types, and operating on arrays is one of the basics we must know.
Let’s take a look at the methods to add elements to JS arrays!
Add new elements at the beginning of the array - unshift()
Test code:
<!DOCTYPE html> <html> <body> <p id="demo">Click the button to add elements to the array.</p> <button onclick="myFunction()">Try it</button> <script> function myFunction() { var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.unshift("Lemon","Pineapple"); var x=document.getElementById("demo"); x.innerHTML=fruits; } </script> <p><b>Note:</b> The unshift() method does not work properly in Internet Explorer 8 and earlier, the values will be inserted, but the return value will be <em>undefined</em>.</p> </body> </html>
Test results :
Lemon,Pineapple,Banana,Orange,Apple,Mango
Add an element at position 2 of the array - splice()
Test code:
<!DOCTYPE html> <html> <body> <p id="demo">Click the button to add elements to the array.</p> <button onclick="myFunction()">Try it</button> <script> function myFunction() { var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(2,0,"Lemon","Kiwi"); var x=document.getElementById("demo"); x.innerHTML=fruits; } </script> </body> </html>
Test result:
Banana,Orange,Lemon,Kiwi,Apple,Mango
Add a new element to the end of the array - push()
Test code:
<!DOCTYPE html> <html> <body> <p id="demo">Click the button to add a new element to the array.</p> <button onclick="myFunction()">Try it</button> <script> var fruits = ["Banana", "Orange", "Apple", "Mango"]; function myFunction() { fruits.push("Kiwi") var x=document.getElementById("demo"); x.innerHTML=fruits; } </script> </body> </html>
Test results:
Banana,Orange,Apple,Mango,Kiwi
Each of these methods has its own benefits. Students who are not familiar with array operations in JS should practice it carefully!
Recommended reading:
Notes on the push method in JavaScript arrays
push() method can Adds one or more elements to the end of an array and returns the new length.Javascript array deduplication/search/insertion/deletion methods
This article is about various operations on arrays.Introduction to the method of deleting specific elements in JavaScript arrays
Deleting specific elements in js arrays is a problem that each of us encountersThe above is the detailed content of Summary of methods for adding elements to JS arrays. For more information, please follow other related articles on the PHP Chinese website!