gpt4 book ai didi

Javascript 数组引用

转载 作者:行者123 更新时间:2023-11-30 07:19:19 25 4
gpt4 key购买 nike

如果我有以下内容:

{"hdrs": ["Make","Model","Year"],
"data" : [
{"Make":"Honda","Model":"Accord","Year":"2008"}
{"Make":"Toyota","Model":"Corolla","Year":"2008"}
{"Make":"Honda","Model":"Pilot","Year":"2008"}]
}

我有一个“hdrs”名称(即“Make”),我如何引用 data 数组实例?似乎 data["Make"][0] 应该可以工作...但无法获得正确的引用

编辑

抱歉含糊不清。我可以遍历 hdrs 来获取每个 hdr 名称,但我需要使用 hdrs 的每个实例值来查找所有数据元素在 data 中(不确定这是更好的解释)。我将把它放在变量 t 中,因为它是 JSON(感谢重新标记)我希望能够引用这样的东西:t.data[hdrs[i ]][j]

最佳答案

我不得不稍微修改一下你的代码:

var x = {"hdrs": ["Make","Model","Year"],
"data" : [
{"Make":"Honda","Model":"Accord","Year":"2008"},
{"Make":"Toyota","Model":"Corolla","Year":"2008"},
{"Make":"Honda","Model":"Pilot","Year":"2008"}]
};

alert( x.data[0].Make );

编辑:回应您的编辑

var x = {"hdrs": ["Make","Model","Year"],
"data" : [
{"Make":"Honda","Model":"Accord","Year":"2008"},
{"Make":"Toyota","Model":"Corolla","Year":"2008"},
{"Make":"Honda","Model":"Pilot","Year":"2008"}]
};
var Header = 0; // Make
for( var i = 0; i <= x.data.length - 1; i++ )
{
alert( x.data[i][x.hdrs[Header]] );
}

关于Javascript 数组引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/86849/

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