JavaScript Glossary: Array unshift() Method

Publikováno: 17.2.2019

Basics

The unshift array method appends a number of values to the start of a given array. It then returns the new length of the array. This method can take a number of argumen...

Celý článek

Basics

The unshift array method appends a number of values to the start of a given array. It then returns the new length of the array. This method can take a number of arguments, each to be added to the array in the specified order.

[1, 2, 3, 4, 5].unshift(0, 0.5)
// [0, 0.5, 1, 2, 3, 4, 5]

https://scotch.io/embed/gist/948919ac330599b8d763d906d6b153b4

Unshift mutates the original array and returns the length of the original array after the mutation.

Syntax

const newArray = oldArray.unshift(item1, item2, ...itemN)

1 Parameter

item[s] This is the element or multiple elements or items to be added.

Returns a number

The method will return the length of the array after adding the new elements.

Common Uses and Snippets

Add new items to an array

Adding new values to the start of an array maintaining a set order.

https://scotch.io/embed/gist/cd1ae883d3c1c87b0ee780341e33d7ce

Add items to cart

The unshift() method can be used to add new items to the front of an array of objects.

https://scotch.io/embed/gist/cbcf983b0225a854d34331b523b894f1

Nahoru
Tento web používá k poskytování služeb a analýze návštěvnosti soubory cookie. Používáním tohoto webu s tímto souhlasíte. Další informace