unshift() 方法會添加一個或多個元素至陣列的開頭,並且回傳陣列的新長度。

語法

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

參數

elementN
欲添加至陣列開頭的元素。

回傳值

呼叫此方法之物件的新 length 屬性值。

描述

unshift 方法會將一或多個給定值插入至一個類陣列(array-like)物件的開頭。

unshift 被刻意設計為具通用性;此方法可以藉由 calledapplied 應用於類似陣列的物件上。若欲應用此方法的物件不包含代表一系列啟始為零之數字屬性序列長度的 length 屬性,可能是不具任何意義的行為。

範例

var arr = [1, 2];

arr.unshift(0); // 執行後的結果是3,其代表處理後的陣列長度
// arr is [0, 1, 2]

arr.unshift(-2, -1); // = 5
// arr is [-2, -1, 0, 1, 2]

arr.unshift([-3]);
// arr is [[-3], -2, -1, 0, 1, 2]

規範

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 Latest Draft (ECMA-262)
The definition of 'Array.prototype.unshift' in that specification.
Draft  

瀏覽器相容性

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidiOS SafariSamsung InternetNode.js
Basic supportChrome Full support 1Edge Full support YesFirefox 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

參見

文件標籤與貢獻者

此頁面的貢獻者: jsgao0, jackblackevo, royxnatw, marktwtn
最近更新: jsgao0,