Array.prototype.shift()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
shift()
方法會移除並回傳陣列的第一個元素。此方法會改變陣列的長度。
嘗試一下
const array1 = [1, 2, 3];
const firstElement = array1.shift();
console.log(array1);
// Expected output: Array [2, 3]
console.log(firstElement);
// Expected output: 1
語法
js
arr.shift()
回傳值
自陣列中移除的元素;若陣列為空,則為 undefined
。
描述
範例
自陣列中移除一個元素
以下的程式碼會印出 myFish
陣列在移除第一個元素之前跟之後的內容,也印出了被移除的元素:
js
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 迴圈中的條件判斷。在下面的例子,每一次迭代都將會自陣列中移除下一個元素,直到陣列空了為止:
js
var names = ["Andrew", "Edward", "Paul", "Chris", "John"];
while ((i = names.shift()) !== undefined) {
console.log(i);
}
// Andrew, Edward, Paul, Chris, John
規範
Specification |
---|
ECMAScript® 2025 Language Specification # sec-array.prototype.shift |
瀏覽器相容性
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
shift |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.