--- title: Array.prototype.unshift() slug: Web/JavaScript/Reference/Global_Objects/Array/unshift translation_of: Web/JavaScript/Reference/Global_Objects/Array/unshift ---
{{JSRef}}

Phương thức unshift() thêm một hoặc nhiều phần tử vào vị trí đầu mảng sau đó trả về chiều dài của mảng mới.

{{EmbedInteractiveExample("pages/js/array-unshift.html")}}

Syntax

arr.unshift(element1[, ...[, elementN]])

Parameters

elementN
Các phần tử được thêm vào đầu mảng.

Return value

Trả về độ dài mới của mảng {{jsxref("Array.length", "length")}}   sau khi thực hiện thêm phần tử.

Description

Phương thức unshift sẽ thêm vào đầu mảng các giá trị được truyền vào.

unshift là "intentionally generic"; Phương thức này có thể được {{jsxref("Function.call", "gọi", "", 1)}} or {{jsxref("Function.apply", "áp dụng", "", 1)}} đối với các đối tượng giống như mảng. Objects which do not contain a length property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner.

Chú ý rằng, Nếu truyền nhiều phần tử vào cùng lức như một biến, chúng sẽ được thêm vào vị trí đầu tiên của mảng, theo đúng vị trí ban đầu mà chúng được truyền vào. Việc gọi phương thức unshift với n phần tử trong một lần sẽ không trả về cùng kết quả (vị trí các phần tử) so với việc gọi n lần với mỗi lần 1 phần tử.

Xem ví dụ bên dưới

let arr = [4,5,6];

arr.unshift(1,2,3);
console.log(arr);
// [1, 2, 3, 4, 5, 6]

arr = [4,5,6]; // resetting the array

arr.unshift(1);
arr.unshift(2);
arr.unshift(3);

console.log(arr);
// [3, 2, 1, 4, 5, 6]

Examples

Using unshift

let arr = [1, 2];

arr.unshift(0); // result of the call is 3, which is the new array length
// arr is [0, 1, 2]

arr.unshift(-2, -1); // the new array length is 5
// arr is [-2, -1, 0, 1, 2]

arr.unshift([-4, -3]); // the new array length is 6
// arr is [[-4, -3], -2, -1, 0, 1, 2]

arr.unshift([-7, -6], [-5]); // the new array length is 8
// arr is [ [-7, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ]

Specifications

Specification Status Comment
{{SpecName('ES3')}} {{Spec2('ES3')}} Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.13', 'Array.prototype.unshift')}} {{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}} {{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}} {{Spec2('ESDraft')}}

Browser compatibility

{{Compat("javascript.builtins.Array.unshift")}}

See also