gpt4 book ai didi

javascript - 如何遍历对象内的数组?

转载 作者:行者123 更新时间:2023-11-29 21:24:04 25 4
gpt4 key购买 nike

我有一个 config.json 文件:

{
"test": {
"maths": [
"core",
"core2"
]
}
}

在我的 index.js 中,我想访问对象“test”,并遍历每个数学元素。

我是数组的新手,所以仍在尝试弄清楚它们是如何工作的。这种方法有什么问题? (我知道它不起作用)

var CONFIG = require('./config.json')

var fn = CONFIG.test.maths

fn.forEach(function(value){
console.log(value);
});

此外,正确的做法是什么?

最佳答案

尝试将 config.js 更改为

module.exports = {
"test": {
"maths": [
"core",
"core2"
]
}
};

就目前而言 - 您的模块不导出任何内容。

更新:如果您更喜欢 .json - 此方法将不起作用,因为 .json 无法导出(但在 Node 中可能需要它,请参阅 How to parse JSON using Node.js? ),它适用于.js 文件作为模块。你也必须改变这部分:

require('./config.js') 

Update2: 它与索引.js

var CONFIG = require('./config')

var fn = CONFIG.test.maths

fn.forEach(function(value){
console.log(value);
});

配置.json

{
"test": {
"maths": [
"core",
"core2"
]
}
}

在我的 Node v5.3.0 中

关于javascript - 如何遍历对象内的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37967873/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com