Home >Daily Programming >HTML Knowledge >How to add new elements to an array in js

How to add new elements to an array in js

藏色散人
藏色散人Original
2018-12-19 16:15:3510199browse

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.

How to add new elements to an array in js

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:

How to add new elements to an array in js

Then use the push method to the array Add two elements "Wei Xiaobao" and "Little Dragon Girl", and the detection is as follows:


How to add new elements to an array in js

Finally, we can output all elements of the new array to the front page through a for loop :

How to add new elements to an array in js

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn