gpt4 book ai didi

jquery - 使用 jQuery 循环 JSON 文件

转载 作者:行者123 更新时间:2023-12-01 04:48:03 24 4
gpt4 key购买 nike

我试图循环遍历这个 JSON 字符串(位于一个名为 language.json 的单独 json 文件中),但没有任何效果

{
"language": [
{
"name": "English Languages",
"values": ["English 1", "English 2", "English 3", "English 4"]
},
{
"name": "French Languages",
"values": ["French 1", "French 2", "French 3", "French 4"]
},
{
"name": "Spanish Languages",
"values": ["Spanish 1", "Spanish 2", "Spanish 3", "Spanish 4"]
}
]}

jQuery

$.getJSON("script/countries.json", function (data) {  
$.each(data.language, function (i, v) {
var category = data[i];
console.log(category.name)
$.each(category.values, function (i, v){
console.log(category.values[i])
});
});

有人可以帮我吗?我想打印语言名称,然后打印它的值列表。

输出:

English Language:
English1
English2..
French Language
French1
French2

等等谢谢!

最佳答案

假设您的回调被调用并且数据具有所需的值。

data[i] 将返回 undefined,因为您正在迭代 data.language,因此您需要使用 varcategory = data.language[i] $.each()会将当前值作为第二个参数传递给回调。所以你可以

//this will iterate through the data.language list and for each item in the array the callback method will be called. 
//The callback method will receive the index of the current item and the item as its 2 parameters
$.each(data.language, function (i, category) {
//here category is the current item in the data.language array so it has the name and values properties
console.log(category.name)
//the same logic follows here, we are iterating through the values array and since it is an array of string calues the second param lang will be the language
$.each(category.values, function (i, lang) {
console.log(lang)
});
});

关于jquery - 使用 jQuery 循环 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26008452/

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