Home  >  Article  >  Web Front-end  >  Summary of methods for adding elements to JS arrays

Summary of methods for adding elements to JS arrays

韦小宝
韦小宝Original
2018-01-26 11:05:223913browse

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:




Click the button to add elements to the array.

Note: The unshift() method does not work properly in Internet Explorer 8 and earlier, the values will be inserted, but the return value will be undefined.

Test results :

Lemon,Pineapple,Banana,Orange,Apple,Mango

Add an element at position 2 of the array - splice()
Test code:




Click the button to add elements to the array.

Test result:

Banana,Orange,Lemon,Kiwi,Apple,Mango

Add a new element to the end of the array - push()
Test code:




Click the button to add a new element to the array.

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 encounters


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

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