简体   繁体   English

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

[英]Check Condition Dynamically usin array : Jquery or Javascript

This is static condition 这是静态的

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

but want to check dynamically suppose my array value is 但要动态检查,假设我的数组值是

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

I want to check condition using above array value something like this 我想使用上面的数组值检查条件,像这样

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

how can possible ? 怎么可能?

You can use Array.prototype.indexOf() on the weblist to filter elements that are in the array weblist 可以使用Array.prototype.indexOf()weblist以过滤在所述阵列元件weblist

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

Polyfill 填充工具

indexOf was added to the ECMA-262 standard in the 5th edition; indexOf已在第5版中添加到ECMA-262标准中; as such it may not be present in all browsers. 因此,它可能并不在所有浏览器中都存在。 You can work around this by utilizing the following code at the beginning of your scripts. 您可以通过在脚本开头使用以下代码来解决此问题。 This will allow you to use indexOf when there is still no native support. 当仍然没有本机支持时,这将允许您使用indexOf。 This algorithm matches the one specified in ECMA-262, 5th edition, assuming TypeError and Math.abs have their original values. 假设TypeError和Math.abs具有其原始值,此算法与ECMA-262,第5版中指定的算法匹配。

Edit 编辑

You can also try using jQuery funciton jQuery.inArray() for better cross browser / version compatibility. 您也可以尝试使用jQuery 函数jQuery.inArray()以获得更好的跨浏览器/版本兼容性。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM