[英]Accessing an associative array using jQuery
我在这里有一个关联数组-
var dataset = {
"person" : [
{"userLabels": ["Name","Role"]},
{"tagNames": ["lName","role"]},
{"tableClass": "width530"},
{"colWidths": ["50%","50%"]}
]
}
我尝试使用jQuery通过各种方法访问“ userLabels”对象,但失败了。 我认为我在基础方面做错了。 我希望使用jQuery访问userLabels对象,并且结果应为数组,因此我可以执行jQuery.inArray()操作。
首先,这是使用现有方法访问数据集的方式。
var dataset =
{
"person" : [
{"userLabels": ["Name","Role"]},
{"tagNames": ["lName","role"]},
{"tableClass": "width530"},
{"colWidths": ["50%","50%"]}
]
};
alert(dataset['person'][0]['userLabels']); //style 1
alert(dataset.person[0]['userLabels']); //style 2
alert(dataset.person[0].userLabels); //style 3
//Also you can use variables in place of specifying the names as well i.e.
var propName ='userLabels';
alert(dataset.person[0][propName]);
//What follows is how to search if a value is in the array 'userLabels'
$.inArray('Name', dataset.person[0].userLabels);
我想问一下您为什么以这种“有趣的方式”进行此操作。 您为什么不只让它们成为所有对象?
如果您是我,这就是我会做的,因为如果您考虑一下,一个人就是一个对象,应该注意, 数组基本上是Javascript中具有'length'属性的对象,尽管我在此不做详细介绍(请随时进行一些研究)。 我猜是因为您不知道如何遍历对象属性。 当然,如果这对您更有意义,那就去做吧。
注意,数组和对象之间的区别之一是需要定义对象属性。 您会注意到,我在下面给了“名称”和“角色”值“未定义”。
无论如何,这是我会做的:
var dataset =
{
"person" : {
"userLabels": {"Name" : undefined,"Role": undefined},
"tagNames": {"lName" : undefined,"role" : undefined},
"tableClass": "width530",
"colWidths": ["50%","50%"]
}
};
for (var i in dataset) { //iterate over all the objects in dataset
console.log(dataset[i]); //I prefer to use console.log() to write but it's only in firefox
alert(dataset[i]); // works in IE.
}
//By using an object all you need to do is:
dataset.person.userLabels.hasOwnProperty('Role'); //returns true or false
无论如何,希望这会有所帮助。
var basic = dataset.person[0].userLabels;
// | | |
// | | --- first element = target object
// | --- person property
// ---- main-object
var userLabels = dataset.person[0].userLabels;
if ($.inArray(yourVal, userLabels) !== -1) {
doStuff();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.