Home  >  Article  >  Web Front-end  >  Detailed graphic explanation of three methods of adding elements to arrays in JavaScript

Detailed graphic explanation of three methods of adding elements to arrays in JavaScript

yulia
yuliaOriginal
2018-10-11 11:38:124476browse

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:

Detailed graphic explanation of three methods of adding elements to arrays in JavaScript

##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() 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:


The above introduces three methods for adding elements to arrays in JS, namely the unshift() method, push() method and splice() method. Which method to choose at work depends on work needs and personal habits. Newbies can try it themselves to deepen their understanding. I hope this article can help you!

For more related tutorials, please visit

JavaScript video tutorial

php public welfare training

The 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!

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