1

我在这里有一个关联数组 -

var dataset = {
    "person" : [    
        {"userLabels": ["Name","Role"]},
        {"tagNames": ["lName","role"]},
        {"tableClass": "width530"},
        {"colWidths": ["50%","50%"]}
    ]
}

我尝试使用各种方法使用 jQuery 访问“userLabels”对象,但失败了。我认为我在基础方面做错了什么。我希望使用 jQuery 访问 userLabels 对象,结果应该是一个数组,所以我可以执行 jQuery.inArray() 操作。

4

3 回答 3

9

首先,这是使用现有方法访问数据集的方法。

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 中具有“长度”属性的对象,尽管我不会在这里详细说明(随意做一些研究)。我猜这是因为您不知道如何迭代对象属性。当然,如果它对你更有意义,那就去吧。

请注意,数组和对象之间的区别之一是需要定义对象属性;你会注意到我在下面给出了 'undefined' 的 'Name' 和 'Role' 值。

无论如何,这就是我要做的:

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

无论如何,希望这会有所帮助。

于 2013-02-09T02:18:46.693 回答
2
var basic = dataset.person[0].userLabels;
//          |        |     |
//          |        |     --- first element = target object
//          |        --- person property
//           ---- main-object
于 2013-02-09T01:42:40.550 回答
0
var userLabels = dataset.person[0].userLabels;
if ($.inArray(yourVal, userLabels) !== -1) {
    doStuff();
}
于 2013-02-09T01:42:40.490 回答