2013-07-06 96 views
0

匹配值我有一個數組是這樣的:獲取和陣列

var Data=[{ 
    "Class":"item1","element":["a","b","c","d","e"], 
    "Class":"item2","element":["a","b","c","d","e"], 
    "Class":"item3","element":["a","b","c","d","e"], 
    "Class":"item4","element":["a","b","c","d","e"] 
}]; 

我有兩個變量:

var class='item1'; 
var element='a'; 

我希望有一個條件,如果VAR類值匹配「物品1」那麼var元素的值應該與它的元素匹配,如:

if(class == Data.Class)then元素應該與它附近的Data.element匹配

有何想法?所有你需要修復的

+5

您的'數據'變量是錯誤的。你怎麼能有相同的鍵/值對4次。只有最後一個將被存儲。 – mohkhan

+0

「Data」數組中的對象重新定義了「Class」和「element」。你是否意味着每一行都是數組中的獨立對象? – freejosh

+0

yes freejosh和什麼應該是它的最佳結構mohkhan – Hushme

回答

2

這應該是您的數據......

var Data= [ 
    { "Class":"item1","element":["a","b","c","d","e"] }, 
    { "Class":"item2","element":["a","b","c","d","e"] }, 
    { "Class":"item3","element":["a","b","c","d","e"] }, 
    { "Class":"item4","element":["a","b","c","d","e"] }, 
]; 

然後你可以遍歷它,找到你的價值。像這樣

var class='item1'; 
var element='a'; 
for(var i = 0; i < Data.length; ++i){ 
    if (Data[i].Class == class){ 
     for(var j = 0; j < Data[i].element.length; ++j){ 
      if (Data[i].elements[j] == element){ 
       // do whatever 
      } 
     } 
    } 
} 
+0

謝謝你我的結構錯了,我失敗了 – Hushme

+0

你能檢查並告訴我這是什麼問題嗎?它不接受相同元素的數據http://jsfiddle.net/StaHg/ – Hushme

0

首先你data

var Data= [ 
    { "Class":"item1","element":["a","b","c","d","e"] }, 
    { "Class":"item2","element":["a","b","c","d","e"] }, 
    { "Class":"item3","element":["a","b","c","d","e"] }, 
    { "Class":"item4","element":["a","b","c","d","e"] }, 
]; 

現在是對象的數組。

然後你就可以考慮這樣做陣列,例如用for

var myclass = "item3"; // class is a reserved word 
for (var i=0; i<Data.length;i++) { 
    if (Data[i].Class == myclass) { 
     // do something with that its data Data[i].element 
    } 
} 
+0

好的課程已匹配它的元素呢? – Hushme

+0

好吧,無論你現在想做什麼..多數民衆贊成在你。你沒有指定你想要的。 – Zim84