Array.prototype.pop()

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

pop() 方法用于 Array 实例,它会移除数组中的最后一个元素,并返回该元素。此方法会改变数组的长度。

试一试

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() 方法读取 thislength 属性。如果归一化后的长度为 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 }

将对象用作类数组

pushpop 方法是通用的,我们可以利用这一点——如下面的示例所示。

请注意,在本例中,我们没有创建一个数组来存储对象的集合。相反,我们将集合存储在对象本身上,并使用 call 方法来调用 Array.prototype.pushArray.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

浏览器兼容性

另见