Home >Daily Programming >HTML Knowledge >How to add new elements to an array in js
js adds new elements to the array, we can use the push method to add. The push() method adds elements to the end of the array and returns the new length of the array.
Below we will introduce to you the js method of adding elements to an array with specific code examples.
The code example is as follows:<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>js往数组中添加新元素的示例</title> </head> <body> <div id="result"></div> <script> var arr = ["朱老师","灭绝","西门"]; arr.push("欧阳克"); console.log(arr); arr.push("韦小宝","小龙女"); console.log(arr); for(var i = 0;i < arr.length; i++){ document.write("<p>" + arr[i] + "</p>"); } </script> </body> </html>In the above code, we first define an array with three elements, and then add a new element "Ouyang Ke" to the original array through the push method, and Use the debugging command
console.log() to output the new array content to the front console, as follows:
push() method adds one or more elements to the end of the array and returns the new length.
push() method can add its parameters to the end of arrayObject in sequence. It directly modifies the arrayObject instead of creating a new array. The push() method and pop() method use the first-in-last-pop function provided by the array.Note: To add one or more elements to the beginning of the array, please use the unshift() method.
This article is an introduction to the method of adding new elements to an array in js. It is also very simple. I hope it will be helpful to friends in need!The above is the detailed content of How to add new elements to an array in js. For more information, please follow other related articles on the PHP Chinese website!