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.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
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 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 gọi or áp dụng đố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 |
---|---|---|
ECMAScript 3rd Edition (ECMA-262) | Standard | Initial definition. Implemented in JavaScript 1.2. |
ECMAScript 5.1 (ECMA-262) The definition of 'Array.prototype.unshift' in that specification. |
Standard | |
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Array.prototype.unshift' in that specification. |
Standard | |
ECMAScript (ECMA-262) The definition of 'Array.prototype.unshift' in that specification. |
Living Standard |
Browser compatibility
BCD tables only load in the browser