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

JavaScript对象赋值给父对象子属性后变为Undefined问题求助

问题原因与解决方案

核心问题:异步时序问题

你的代码里,getData()是异步操作,then回调会在异步请求完成后才执行,但如果你的console.log(typeof(personalityData.ENFP))是写在getData().then(...)之后的同步代码,这行log会先于回调执行——此时personalityData.ENFP还没被赋值,自然返回undefined。

解决方案1:将打印逻辑放在then回调内部

确保赋值完成后再执行打印操作:

var personalityData = {}
var getData = async function () {
            const res = await fetch("url")
            if (res.status == 500) {
                return '500 Error';
            } else if (!res.ok) {
                return 'response is not ok';
            }
            const jsonData = await res.json();
            return jsonData;
    }
getData().then(response => {
  personalityData.ENFP = response;
  // 此时再打印就能得到正确结果
  console.log(typeof(response)); // object
  console.log(typeof(personalityData.ENFP)); // object
  console.log(typeof(personalityData)); // object
}); 

解决方案2:用async/await替代then,让代码逻辑更线性

通过自执行async函数包裹,避免回调嵌套,同时保证时序:

var personalityData = {}
var getData = async function () {
            const res = await fetch("url")
            if (res.status == 500) {
                return '500 Error';
            } else if (!res.ok) {
                return 'response is not ok';
            }
            const jsonData = await res.json();
            return jsonData;
    }

// 自执行async函数
(async function() {
  const response = await getData();
  personalityData.ENFP = response;
  // 打印逻辑在赋值后执行
  console.log(typeof(response));
  console.log(typeof(personalityData.ENFP));
  console.log(typeof(personalityData));
})();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 22:02:01