gpt4 book ai didi

javascript - 通过动态变量访问 Json 值

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

好的,首先是 json 结构

[{
"type": "button",
"name": "Off",
"tabname": "1",
"image_file": "path\\Off.gif"
}, {
"type": "button",
"name": "Off1",
"tabname": "2",
"image_file": "path\\Off1.gif",
"image_file_1": "path\\On1.gif"
}, {
"type": "button",
"name": "Off2",
"tabname": "3",
"image_file": "path\\Off2.gif",
"image_file_1": "path\\On2.gif",
"image_file_2": "path\\half.gif"
}
]

image_file 字段可以有多个条目(即 image_file、image_file_1、image_file_2 等),我如何在循环中动态访问它?

当前不工作的代码(只是相关的东西)

$.each(data, function (i, item) {
var images = [];
imageIndex = 1;
continueLoop = true;
while(continueLoop) {
if(imageIndex == 1) {
images.push(data[i].image_file);
}
else {
var testVal = 'image_file_' + imageIndex;
alert(data[i][testVal]);
if(data[i][testVal] === undefined) {
continueLoop = false;
}
else {
images.push(data[i][testVal]);

}
}
imageIndex++;
}
});

第一次迭代工作正常(即 if (imageIndex == 1) 位),但是我放入的 else 子句警报总是测试值返回未定义

任何帮助将不胜感激

最佳答案

据我了解您的代码,您将获得所有 image_file 属性,甚至是带有数字的属性。 You can easily do it with this :

var images = [];

//iterate through the array
$.each(data, function (i, item) {

//iterate through each property
$.each(item, function (key, value) {

//if the property starts with image_file, push into the array
if (key.indexOf('image_file') === 0) images.push(value);
});
});

console.log(images); // ["path\\Off.gif","path\\Off1.gif","path\\On1.gif","path\\Off2.gif","path\\On2.gif","path\\half.gif"]

关于javascript - 通过动态变量访问 Json 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16995333/

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