試一試
const plants = ["broccoli", "cauliflower", "cabbage", "kale", "tomato"];
console.log(plants.pop());
// Expected output: "tomato"
console.log(plants);
// Expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"]
plants.pop();
console.log(plants);
// Expected output: Array ["broccoli", "cauliflower", "cabbage"]
語法
js
pop()
引數
無。
返回值
從陣列中移除的元素;如果陣列為空,則返回 undefined。
描述
pop() 方法移除陣列的最後一個元素,並將其值返回給呼叫者。如果你在一個空陣列上呼叫 pop(),它會返回 undefined。
Array.prototype.shift() 的行為與 pop() 類似,但應用於陣列的第一個元素。
pop() 方法是一個可變方法。它會改變 this 的長度和內容。如果你想使 this 的值保持不變,但返回一個移除了最後一個元素的陣列,你可以使用 arr.slice(0, -1) 來代替。
pop() 方法是 通用的。它只期望 this 值具有 length 屬性和整數鍵屬性。儘管字串也是類陣列的,但此方法不適用於它們,因為字串是不可變的。
示例
移除陣列的最後一個元素
以下程式碼建立了 myFish 陣列,其中包含四個元素,然後移除了它的最後一個元素。
js
const myFish = ["angel", "clown", "mandarin", "sturgeon"];
const popped = myFish.pop();
console.log(myFish); // ['angel', 'clown', 'mandarin' ]
console.log(popped); // 'sturgeon'
在非陣列物件上呼叫 pop()
pop() 方法讀取 this 的 length 屬性。如果歸一化後的長度為 0,則 length 會被再次設定為 0(儘管之前它可能是負數或 undefined)。否則,會返回 length - 1 處的屬性,並將其刪除。
js
const arrayLike = {
length: 3,
unrelated: "foo",
2: 4,
};
console.log(Array.prototype.pop.call(arrayLike));
// 4
console.log(arrayLike);
// { length: 2, unrelated: 'foo' }
const plainObj = {};
// There's no length property, so the length is 0
Array.prototype.pop.call(plainObj);
console.log(plainObj);
// { length: 0 }
將物件用作類陣列
push 和 pop 方法是通用的,我們可以利用這一點——如下面的示例所示。
請注意,在本例中,我們沒有建立一個數組來儲存物件的集合。相反,我們將集合儲存在物件本身上,並使用 call 方法來呼叫 Array.prototype.push 和 Array.prototype.pop,以欺騙這些方法,讓它們以為我們正在處理一個數組。
js
const collection = {
length: 0,
addElements(...elements) {
// obj.length will be incremented automatically
// every time an element is added.
// Returning what push returns; that is
// the new value of length property.
return [].push.call(this, ...elements);
},
removeElement() {
// obj.length will be decremented automatically
// every time an element is removed.
// Returning what pop returns; that is
// the removed element.
return [].pop.call(this);
},
};
collection.addElements(10, 20, 30);
console.log(collection.length); // 3
collection.removeElement();
console.log(collection.length); // 2
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-array.prototype.pop |
瀏覽器相容性
載入中…