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

JavaScript跨模块引用嵌套对象报错:'person未定义'求解答

问题分析与修复方案

核心错误点

  • 属性访问未使用正确的标识符形式
    在main.js中,configSettings[person][name]里的person和name会被JS引擎当作变量解析,但你并没有定义这两个变量,因此直接抛出person is not defined错误。正确的属性访问方式有两种:

    • 点语法(推荐,更直观):configSettings.person.name
    • 方括号语法(需用字符串包裹属性名):configSettings['person']['name']
  • 字符串未加引号
    config.settings.js里的color: blue中,blue没有被引号包裹,会被当作变量处理,但你并未定义该变量,运行时会额外抛出blue is not defined错误,需改为'blue'。

  • 模块引用路径错误
    本地模块引用时,需添加相对路径前缀./,否则Node.js会默认去node_modules目录查找包,导致找不到本地的config.settings.js。


修正后的代码

config.settings.js

var configs = {
    person: {
        'name': 'John',
        'number': 27,
        'color': 'blue'
    },
    place: {
        'town': 'springville',
        'population': 201827
    }
}
module.exports = configs;

main.js

var configSettings = require('./config.settings');
module.exports = {
    run: function(){
        console.log(configSettings.person.name);
        // 或使用方括号语法:console.log(configSettings['person']['name']);
   }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 09:33:33