試一試
const array = [1, 2, 3];
const firstElement = array.shift();
console.log(array);
// Expected output: Array [2, 3]
console.log(firstElement);
// Expected output: 1
語法
js
shift()
引數
無。
返回值
從陣列中移除的元素;如果陣列為空,則返回 undefined。
描述
shift() 方法將所有值向左移動 1 位,並將長度減 1,從而移除第一個元素。如果 length 屬性為 0,則返回 undefined。
pop() 方法與 shift() 的行為類似,但作用於陣列的最後一個元素。
shift() 方法是 變異方法。它會改變 this 的長度和內容。如果您希望 this 的值保持不變,但返回一個移除第一個元素的新陣列,可以使用 arr.slice(1) 來代替。
shift() 方法是 通用的。它只要求 this 值具有 length 屬性和整數鍵屬性。儘管字串也類似陣列,但此方法不適用於字串,因為字串是不可變的。
示例
移除陣列中的元素
以下程式碼顯示了 myFish 陣列在移除第一個元素之前和之後的狀態。它還顯示了被移除的元素。
js
const myFish = ["angel", "clown", "mandarin", "surgeon"];
console.log("myFish before:", myFish);
// myFish before: ['angel', 'clown', 'mandarin', 'surgeon']
const 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
const names = ["Andrew", "Tyrone", "Paul", "Maria", "Gayatri"];
while (typeof (i = names.shift()) !== "undefined") {
console.log(i);
}
// Andrew, Tyrone, Paul, Maria, Gayatri
在非陣列物件上呼叫 shift()
shift() 方法讀取 this 的 length 屬性。如果 規範化的長度 為 0,則 length 會再次設定為 0(而之前它可能是負數或 undefined)。否則,將返回索引為 0 的屬性,並將其餘屬性向左移動一位。索引為 length - 1 的屬性將被 刪除,並且 length 屬性會減一。
js
const arrayLike = {
length: 3,
unrelated: "foo",
2: 4,
};
console.log(Array.prototype.shift.call(arrayLike));
// undefined, because it is an empty slot
console.log(arrayLike);
// { '1': 4, length: 2, unrelated: 'foo' }
const plainObj = {};
// There's no length property, so the length is 0
Array.prototype.shift.call(plainObj);
console.log(plainObj);
// { length: 0 }
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-array.prototype.shift |
瀏覽器相容性
載入中…