Home > Web Front-end > JS Tutorial > Detailed explanation of 3 ways to add elements at the beginning of JavaScript arrays

Detailed explanation of 3 ways to add elements at the beginning of JavaScript arrays

青灯夜游
Release: 2021-04-28 12:51:13
forward
7732 people have browsed it

This article will introduce you to 3 methods of adding 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.

Detailed explanation of 3 ways to add elements at the beginning of JavaScript arrays

#Today, let’s learn how to add elements to the beginning of an array.

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"]
Copy after login

2.Use 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"]
Copy after login

3.Use Array.concat()

We can also use the concat() 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"]
Copy after login

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

Author: Orkhan Jafarov

Translation address: https://segmentfault.com/a/1190000039129785

For more programming-related knowledge, please visit: Programming Video! !

The above is the detailed content of Detailed explanation of 3 ways to add elements at the beginning of JavaScript arrays. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template