2014-05-19 13 views
2

這是靜態的條件檢查狀況動態全光照陣列:jQuery的或Javascript

var as = $(json).filter(function (i, n) { 
    return n.website === 'yahoo' || n.website === 'ebay' 
}); 

,但要檢查動態假設我的陣列值

weblist[0] = "yahoo"; 
weblist[1] = "google"; 
weblist[2] = "ebay"; 
weblist[3] = "rediff"; 
weblist[4] = "amazon"; 

我想用上面陣列有價值的東西來檢查條件像這樣

var as = $(json).filter(function (i, n) { 
    return n.website === 'yahoo' || n.website === 'google' || n.website === 'ebay' || n.website === 'rediff' || n.website === 'amazon' 
}); 

怎麼可能?

回答

5

可以使用Array.prototype.indexOf()weblist以過濾是數組中的元素weblist

var as=$(json).filter(function (i,n){ 
    return weblist.indexOf(n.website) !== -1 
}); 

Polyfill

的indexOf加入到在第5版的ECMA-262標準;因此它可能不會出現在所有瀏覽器中。您可以通過在腳本開始處使用following code來解決此問題。這將允許您在沒有本地支持的情況下使用indexOf。此算法與ECMA-262第5版中指定的算法相匹配,假定TypeError和Math.abs具有其原始值。

編輯

您也可以嘗試使用jQuery功能可按jQuery.inArray()更好的跨瀏覽器/版本的兼容性。

+0

感謝@Cerbrus,更新。 – Adil

+1

如果你只需要支持IE9 +是 –

+0

如果您需要支持舊版本的IE,有一個[填充工具](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Polyfill)MDN網站Adil鏈接。 – Cerbrus

1
var as = $(json).filter(function (i,n){ 
    return $.inArray(n.website, weblist) >= 0; 
}); 
+2

我想知道爲什麼有人低估了這個答案,因爲這是正確的(jQuery)方法。 +1。 – Cerbrus