迭代对象以查看是否找到相同的值

时间:2013-12-02 05:34:59

标签: javascript jquery

我想在下面的陈述中搜索对象并查看它们是否包含相同的值。

$.each( winning, function( idx, obj ) {

}); 

我的对象如下:

var winning = [{1:0, 2:0, 3:0},{4:0, 5:0, 6:0},{7:0, 8:0, 9:0},
                     {1:0, 4:0, 7:0},{2:0, 5:0, 8:0},{3:0, 6:0, 9:0},
                     {1:0, 5:0, 9:0},{7:0, 5:0, 3:0}];

因此,我想说看一下对象数组中的对象是否具有1的所有值。因此{1:1, 2:1, 3:1}将返回true,但{1:1, 2:0, 3:1}将返回false。这可能吗?我能看到它完成的唯一方法是为每个单独的对象创建大量的循环。我对jQuery或JavaScript不是很熟悉。

3 个答案:

答案 0 :(得分:1)

您可以使用hasOwnProperty ...

function checkForOne()
{
$(winning).each(function(i) {              
 for (var i in this) {
        if(this.hasOwnProperty(i)){
            if(this[i]==1)
            {
                alert("contains 1"); return false;
            }
        }
    }
});
   return true;
}

答案 1 :(得分:1)

尝试:

var winning = [{1:0, 2:0, 3:0},{4:0, 5:0, 6:0},{7:0, 8:0, 9:0},
                     {1:0, 4:0, 7:0},{2:0, 5:0, 8:0},{3:0, 6:0, 9:0},
                     {1:0, 5:0, 9:0},{7:0, 5:0, 3:0},{7:1, 5:1, 3:1},{7:-1, 5:-1, 3:-1},{7:-1, 5:-1, 3:0},{7:2, 5:2, 3:2}];
var len = winning.length;
for(var i=0;i<len;i++){
    var data = winning[i];
    var txt = "";
    var val = [];
    var flg = 1;
    $.each(data,function(k,v){
        val.push(v);
        txt += k+":"+v+" ";
    });
    var vlen = val.length;
    for(var j=0;j<vlen;j++){
        for(var k=j+1;j<vlen;j++){
            if(val[j] != val[k]){
                flg = 0;
                break;
            }
        }
    }
    if(flg == 0){        
        txt += " false";
    }
    else{
        if(val[0] == 0){
            txt += " false";
        }
        else if(val[0] == 1){
            txt += " true 1";
        }
        else if(val[0] == -1){
            txt += " true -1";
        }
        else if(val[0] == 2){
            txt += " true 2";
        }
    }
    $("body").append("<div>"+txt+"</div>");
}

Fiddle here.

答案 2 :(得分:0)

使用你的例子......

$.each( winning, function( idx, obj ) {
    var groupSum = obj.reduce(function(previousValue, currentValue, index, array){
        return previousValue + currentValue;
    });
    if (groupSum == 3 || groupSum == -3) alert('Identicals');
});