使用数组动态检查条件:Jquery或Javascript

时间:2014-05-19 07:34:33

标签: javascript jquery arrays

这是静态条件

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'
});

怎么可能?

2 个答案:

答案 0 :(得分:5)

您可以使用weblist上的Array.prototype.indexOf()来过滤数组weblist

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

<强> Polyfill

indexOf被添加到第5版的ECMA-262标准中;因此,它可能不会出现在所有浏览器中。您可以使用脚本开头的following code来解决此问题。这将允许您在仍然没有本机支持时使用indexOf。假设TypeError和Math.abs具有原始值,此算法与ECMA-262第5版中指定的算法匹配。

修改

您还可以尝试使用jQuery funciton jQuery.inArray()以获得更好的跨浏览器/版本兼容性。

答案 1 :(得分:1)

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