You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

数组解构剩余属性中的对象解构模式含义及pop/push方法使用疑问

问题解答

问题1:作为数组解构模式剩余属性的对象解构模式代表什么?

在常规数组解构里,...rest是把未被解构的剩余元素收集成新数组,但这里的...{ pop, push }是特殊用法:

  • 剩余操作符...没有收集数组元素,而是直接指向原数组对象本身
  • 后面的{ pop, push }是对象解构语法,作用是从原数组对象上提取它的pop和push方法(数组本质是对象,继承了Array.prototype上的内置方法)
  • 这种写法本质是对数组对象做属性提取,而非对数组元素做收集,等价于先解构数组元素,再单独从原数组上解构方法:
const arr = [1, 2];
const a = arr[0];
const b = arr[1];
const { pop, push } = arr;

问题2:上述代码中的pop和push函数是什么?该如何使用?

pop和push是Array.prototype上的内置方法,原本需要通过数组实例调用,调用时方法内部的this会指向该数组。

直接调用报错的原因

示例代码里只是把pop和push函数本身从数组上解构出来,但没绑定原数组的上下文(即this指向)。直接调用时,严格模式下函数内部的this是undefined,而数组方法要求this必须是数组对象,因此会抛出Cannot convert undefined or null to object的错误。

正确使用方式

有几种方法可以正常调用这些解构出来的方法:

  1. 用bind绑定原数组上下文:
const [a, b, ...{ pop, push }] = [1, 2];
const targetArr = [1, 2];
const boundPop = pop.bind(targetArr);
const boundPush = push.bind(targetArr);
console.log(boundPop()); // 2
console.log(boundPush(3)); // 3
  1. 用call/apply指定调用时的this:
const [a, b, ...{ pop, push }] = [1, 2];
const targetArr = [1, 2];
console.log(pop.call(targetArr)); // 2
push.call(targetArr, 3);
console.log(targetArr); // [1, 3]
  1. 直接通过原数组实例调用(更简洁):
    其实没必要单独解构方法,直接操作原数组更清晰:
const arr = [1, 2];
const [a, b] = arr;
console.log(arr.pop()); // 2
arr.push(3);
console.log(arr); // [1, 3]

内容的提问来源于stack exchange,提问作者Géry Ogam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 23:07:23