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

调用JavaScript函数更新对象时返回undefined的问题求解

问题原因

你编写的updateCollection函数没有设置显式返回值,JavaScript 中所有没有明确写return语句的函数,执行后默认返回undefined,所以你直接打印函数调用结果就会输出undefined。

修复方案

根据使用需求,有两种常用修改方式:

方案1:让函数返回更新后的完整集合对象

在函数末尾添加return语句即可,修改后的函数代码如下:

function updateCollection(id, prop, value) {
  if (value === "") {
    delete collection[id][prop];
  } else if (prop === "Age") {
    collection[id][prop] = collection[id][prop] || [];
    collection[id][prop].push(value);
  } else {
    collection[id][prop] = value;
  }
  // 新增返回语句
  return collection;
}

修改后调用console.log(updateCollection("993736", "Age", "42x6x259")),就会正常输出更新后的完整集合对象。

方案2:直接打印更新后的集合,不需要获取函数返回值

如果不需要用到函数的返回结果,调整打印语句的参数即可:

// 先执行更新操作
updateCollection("993736", "Age", "42x6x259");
// 直接打印集合对象
console.log(collection);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 19:15:02