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 类值匹配“item1”,那么 var 元素值应该与其元素匹配,例如:

if (class == Data.Class) then element 应该与它附近的 Data.element 匹配

有任何想法吗?

4

2 回答 2

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
            }
        }
    }
}
于 2013-07-06T13:20:12.723 回答
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
    }
}
于 2013-07-06T13:14:18.527 回答