shift() 方法會移除並回傳陣列的第一個元素。此方法會改變陣列的長度。

語法

arr.shift()

回傳值

自陣列中移除的元素;若陣列為空,則為 undefined

描述

shift 方法會移除並回傳陣列中索引值為零之元素(即第一個元素),並將隨後的其他索引值減一。假如 length 屬性值為 0,則會回傳 undefined

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

範例

自陣列中移除一個元素

以下的程式碼會印出 myFish 陣列在移除第一個元素之前跟之後的內容,也印出了被移除的元素:

var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];

console.log('myFish before:', JSON.stringify(myFish));
// myFish before: ['angel', 'clown', 'mandarin', 'surgeon']

var shifted = myFish.shift(); 

console.log('myFish after:', myFish); 
// myFish after: ['clown', 'mandarin', 'surgeon']

console.log('Removed this element:', shifted); 
// Removed this element: angel

於 while 迴圈中使用 shift() 方法

shift() 方法常被用在 while 迴圈中的條件判斷。在下面的例子,每一次迭代都將會自陣列中移除下一個元素,直到陣列空了為止:

var names = ["Andrew", "Edward", "Paul", "Chris" ,"John"];

while( (i = names.shift()) !== undefined ) {
    console.log(i);
}
// Andrew, Edward, Paul, Chris, John

規範

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.shift' in that specification.
Standard  
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Array.prototype.shift' in that specification.
Standard  
ECMAScript Latest Draft (ECMA-262)
The definition of 'Array.prototype.shift' 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

參見

文件標籤與貢獻者

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