带有变量的 Javascript 对象表示法 [英] Javascript Object notation with variable
本文介绍了带有变量的 Javascript 对象表示法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的 PHP 脚本 specs.php 输出如下:
<预><代码>{高清": {方面": ["1920x1080","1920x1080","1920x1080"],尺寸":["603 KB","265 KB",438 KB"]},中等的": {方面": ["800x530","800x530",800x530"],尺寸":["198 KB","105 KB",152 KB"]},状态":成功"}使用 jQuery 我加载 JSON 并将其分配给 specs_obj
我可以使用 specs_obj 访问第一项的中等"尺寸".中等大小[0]
如何在点符号中使用变量?
var specs_obj;$.post("specs.php", {},功能(数据){if (data.status == "success") {specs_obj = 数据;writeSizes("中");} 别的 {}}, "json");函数 writeSizes(预设){//测试从第一个文件中获取中等尺寸var size = specs_obj.中等大小[0];//var size = specs_obj.preset.sizes[0];}
解决方案
不能在点表示法中使用变量,但可以使用括号表示法:
var size = specs_obj[preset].sizes[0];
如果 preset
包含字符串medium",则在功能上等同于:
var size = specs_obj.medium.sizes[0];
My PHP script specs.php outputs the following:
{
"hd": {
"dimensions": [
"1920x1080",
"1920x1080",
"1920x1080"
],
"sizes": [
"603 KB",
"265 KB",
"438 KB"
]
},
"medium": {
"dimensions": [
"800x530",
"800x530",
"800x530"
],
"sizes": [
"198 KB",
"105 KB",
"152 KB"
]
},
"status": "success"
}
With jQuery I load in the JSON and assign it to specs_obj
I can access the first item's "medium" "sizes" with specs_obj. medium.sizes[0]
How can I use a variable in the dot notation?
var specs_obj;
$.post("specs.php", {},
function(data) {
if (data.status == "success") {
specs_obj = data;
writeSizes("medium");
} else {}
}, "json"
);
function writeSizes(preset) {
// test get medium dimensions from first file
var size = specs_obj. medium.sizes[0];
// var size = specs_obj.preset.sizes[0];
}
解决方案
You can't use a variable in the dot notation, but you can use brackets notation:
var size = specs_obj[preset].sizes[0];
If preset
contains the string "medium", that's functionally identical to:
var size = specs_obj.medium.sizes[0];
这篇关于带有变量的 Javascript 对象表示法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文