Home>Article>Web Front-end> A brief discussion on several methods of adding new elements to the beginning of an array in JavaScript

A brief discussion on several methods of adding new elements to the beginning of an array in JavaScript

青灯夜游
青灯夜游 forward
2021-03-23 09:59:54 2240browse

This article will introduce to you how to add elements to the beginning of an array in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

A brief discussion on several methods of adding new elements to the beginning of an array in JavaScript

#Today, let’s learn how to add an element to the first element of the element.

1.Array.unshift()

let fruits = ["Apple", "Banana", "Mango"]; fruits.unshift("Orange"); console.log(fruits); // Prints ["Orange", "Apple", "Banana", "Mango"] fruits.unshift("Guava", "Papaya"); console.log(fruits); // Prints ["Guava", "Papaya", "Orange", "Apple", "Banana", "Mango"]

2.Use the spread operator (...)

var fruits = ["Apple", "Banana", "Mango"]; var moreFruits = ["Orange", ...fruits]; console.log(moreFruits); // Prints ["Orange", "Apple", "Banana", "Mango"] var someoMoreFruits = ["Guava", "Papaya", ...moreFruits]; console.log(someoMoreFruits); // Prints ["Guava", "Papaya", "Orange", "Apple", "Banana", "Mango"] console.log(fruits); // Prints ["Apple", "Banana", "Mango"]

3. Use Array.concat()

We can also use theconcat()method to concatenate two (or more) arrays at the beginning.

var fruits = ["Apple", "Banana", "Mango"]; var moreFruits = ["Orange"]; var someoMoreFruits = ["Guava", "Papaya"]; var allFruits = someoMoreFruits.concat(moreFruits, fruits); console.log(allFruits); // Prints ["Guava", "Papaya", "Orange", "Apple", "Banana", "Mango"]

Original address: https://codingnconcepts.com/javascript/how-to-add-element-at-beggining-of-javascript-array/

For more programming-related knowledge, please visit:programming video! !

The above is the detailed content of A brief discussion on several methods of adding new elements to the beginning of an array in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete