2011-12-09 40 views
2

我正在嘗試修改一個插件,以便它可以在組內使用「OR」邏輯並在組之間使用「AND」邏輯。這是working example。我的代碼如下所示:如何在jQuery中實現「OR」邏輯而不是「AND」?

if ($.inArray(tag, itemTags) > -1) { 
    return true; 
} 

如果我有["One","Two"]tag如何實現或邏輯。它。

+0

'或'或'XOR'? –

+1

你能更詳細地描述你想要做什麼嗎?你的問題太簡單了,以找出你的要求。請提供插件應該執行的示例。 – jfriend00

+0

我需要在羣組內實現「或」,在羣組之間實現「和」 – Imran

回答

1

如果你的目標瀏覽器提供array.filter,你可以做這樣的:

var matchingTags = itemTags.filter(function(el) { 
         return $.inArray(el, tag) > -1; 
        }); 

See it in action

1

使用ES5的.some方法,這可以是相當簡潔。舊版瀏覽器有a shim

var tag = ["d", "b"], 
    tagItems = ["a", "b", "c", "d", "e"]; 

var contains = tagItems.some(function(v) { // whether at least "d" or "b" is in `tagItems` 
    return ~tag.indexOf(v); 
}); 

if(contains) { 
    // ... 

這表現爲這個tagItems如下:

tag = ["d", "b"];  // contains === true (due to "d") 
tag = ["foo", "x", "a"]; // contains === true (due to "a") 
tag = ["bar"];   // contains === false (due to no matches) 

你也可以彌補這方面的輔助功能:

$.inArrayMultiple = function(subset, arr) { 
    return arr.some(function(v) { 
     return ~subset.indexOf(v); 
    }); 
}; 

然後你可以使用:

if($.inArrayMultiple(tag, itemTags)) { 
    // ... 
1

迂迴的解決方案是將inArray條件包裝在$(array).each()函數中,該函數在數組中存在任何迭代項目時返回true。

var result = function() 
{ 
    var r = false; 
    $(tag).each(function() 
    { 
     if ($.inArray(this, itemTags) > -1) 
     { 
      r = true; 
     } 
    }); 
    return r; 
}