簡體   English   中英

使用jQuery訪問關聯數組

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM