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

JavaScript中直接访问对象属性出现undefined错误的原因咨询

直接访问对象属性出现undefined错误的原因分析

原始数据与目标需求

原始的location数组:

var location = [
    { continent: 'Africa',  country: 'Nigeria', population: 200 },
    { continent: 'Europe', country: 'Germany', population: 120 },
    { continent: 'Europe', country: 'Spain',  population: 100  },
    { continent: 'Asia', country: 'China', population: 500 },
    { continent: 'Africa',  country: 'Kenya', population: 70 },
    { continent: 'Europe', country: 'Poland',  population: 90 },
];

目标是生成按大洲分组的国家列表:

{
  Africa: [ 'Nigeria', 'Kenya' ],
  Europe: [ 'Germany', 'Spain', 'Poland' ],
  Asia: [ 'China' ]
}

错误代码及问题

尝试直接访问属性的代码运行时持续出现undefined错误:

var output = {};
for (let i = 0; i < location.length; i++){
    //var cont = location[i].country;
    //var fName = location[i].continent;
    
    if (output.hasOwnProperty(location[i].continent)){        
        output.location[i][continent].push(location[i].country);
    }else{
        output.location[i][continent] = [];
        output.location[i].continent.push(location[i].country);
    }

}
console.log(output);

错误原因解析

这段代码跑不起来完全是因为对象属性访问的语法用错了,具体问题有三个:

  • 第一,output.location[i]完全是错误写法。output一开始是空对象,根本没有location这个属性,直接访问会得到undefined,后续再访问[continent]必然报错。你实际要操作的是output里以当前大洲名称为键的属性,而非output下的location属性。
  • 第二,[continent]中的continent是未定义的变量,不是你想要的当前遍历项的大洲值。你需要写成[location[i].continent]才对,直接写continent的话,JS会把它当成全局变量,而这个变量根本不存在,值为undefined,自然找不到对应属性。
  • 第三,output.location[i].continent.push(...)同时犯了上面两个错误:既错误访问了不存在的output.location属性,又误用了未定义的continent变量,报错是必然结果。

正确代码的逻辑

将属性值存入变量后代码能正常运行,本质是用变量fName和cont存储了正确的属性值,避免了语法误用:

var output = {};
for (let i = 0; i < location.length; i++){
    var cont = location[i].country;
    var fName = location[i].continent;
    
    if (output.hasOwnProperty(location[i].continent)){        
        output[fName].push(cont);
    }else{
        output[fName] = [];
        output[fName].push(cont);
    }
}
console.log(output);

这里output[fName]是正确的方括号属性访问语法,用变量fName的值作为output对象的键,精准访问到对应大洲的数组,自然不会出现undefined错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 00:02:40