unshift() 方法将一个或多个元素添加到数组的开头,并返回该数组的新长度。

语法

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

参数列表

elementN
要添加到数组开头的元素。

返回值

当一个对象调用该方法时,返回其 length 属性值。

描述

unshift 方法会在调用它的类数组对象的开始位置插入给定的参数。

unshift 特意被设计成具有通用性;这个方法能够通过 callapply 方法作用于类数组对象上。不过对于没有 length 属性(代表从0开始的一系列连续的数字属性的最后一个)的对象,调用该方法可能没有任何意义。

Please note that, if multiple elements are passed as parameters, they're inserted in chunk at the beginning of the object, in the exact same order they were passed as parameters. Hence, calling unshift with n arguments once, or calling it n times with 1 argument (with a loop, for example), don't yield the same results. See example:

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]

示例

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 ]

规范

规范 状态 备注
ECMAScript 3rd Edition (ECMA-262) Standard Initial definition. Implemented in JavaScript 1.2.
ECMAScript 5.1 (ECMA-262)
Array.prototype.unshift
Standard  
ECMAScript 2015 (6th Edition, ECMA-262)
Array.prototype.unshift
Standard  
ECMAScript Latest Draft (ECMA-262)
Array.prototype.unshift
Draft  

浏览器兼容性

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
unshiftChrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 5.5Opera Full support YesSafari Full support YesWebView Android Full support YesChrome Android Full support YesEdge Mobile Full support YesFirefox Android Full support 4Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs Full support Yes

Legend

Full support  
Full support

参见