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

JavaScript中数组push操作返回1而非预期数组问题求助

问题原因

你遇到的现象是Array.push()方法的标准设计,不属于代码逻辑错误:

  • JavaScript/TypeScript中,push() 方法的返回值为执行插入操作后数组的最新长度,而非修改后的数组本身。
  • 你向初始为空的ctx.emails数组中插入1个元素,返回值为1属于完全符合规范的正常结果。

验证方法

执行完push操作后直接打印ctx.emails,即可得到你预期的['sethborne@gmail.com']结果,参考代码如下:

const req = {
  ctx: {
    emails: [],
    newInvitationDto: {
      _type: 'NewInvitationDto',
      email: 'sethborne@gmail.com',
      groupId: '12345678',
      roleIds: ['organization.doctor'],
      firstName: 'Seth',
      lastName: 'Borne',
      title: 'Doctor',
      phone: '212.555.1212',
    },
  },
};

const ctx: Invitation = <Invitation>req.ctx;
const pushRes = ctx.emails.push(ctx.newInvitationDto.email);

console.log(pushRes); // 输出 1:数组新长度
console.log(ctx.emails); // 输出 ['sethborne@gmail.com']:符合预期的数组内容

扩展:直接获取新数组的写法

如果你需要在插入元素的同时直接拿到修改后的数组,可使用扩展运算符生成新数组:

const updatedEmails = [...ctx.emails, ctx.newInvitationDto.email];
console.log(updatedEmails); // 直接返回 ['sethborne@gmail.com']

内容的提问来源于stack exchange,提问作者Daniel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 03:24:03