javascript - 检查数组中的值

标签 javascript arrays for-loop match

我正在尝试使用PURE JAVASCRIPT检查数组中的匹配情况。我不知道该怎么做,非常感谢您的帮助。

var sites = new Array ("site1.com", "site2.com", "site3.com" ...);
// Sites array contains 100 values

var imgs = document.getElementsByTagName("img");
    for (var i = 0; i < imgs.length; i++) {
        img = imgs[i].src;

        // I'm trying to check if is in array, 
        // and don't waste a lot of size in code

        if(img.match(sites)){
            notHere(imgs[i]);
        }

        // This is the working way.
        // Even if location is a.site1.com/b/, it will match 
        if (img.match("site1.com")) {
            heReload(imgs[i]);
        }
        // Repeat this piece of code 100 times
    }
}

注意:我不想检查确切的值。我想模拟 match() 函数,因此如果 img = "http://a.b.c/d/"并且数组中是 "b.c/",它会执行 function()

最佳答案

您的“sites”变量应该是正则表达式而不是数组:

 var sites = /\b(site1\.com|site2\.com|etc|etc)\b/

稍后:

 if (img.match(sites))
    ......

如果出于某种原因您更喜欢将“站点”保留在数组中,您还可以“即时”创建正则表达式:

var sites = ["site1.com", "site2.com", "site3.com"]
var sitesRegexp = new RegExp("\\b(" + sites.join("|").replace(".", "\\.") + ")\\b")

 ....

 if (img.match(sitesRegexp)
    ......

关于javascript - 检查数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10385681/

相关文章:

arrays - Julia 中数组数组的逐元素操作

javascript - 我可以使用 JavaScript 在 URL 中添加内容吗?

javascript - 附加 div block 并自动更改行

php - 删除域上的重复 cookie

python - numpy 重复元素

for-loop - 打破 Julia 中的循环

javascript - 使用PHP、MSSQL、Jquery进行即时搜索

java - 从对象数组中删除对象

c++ - 使用 for 循环删除 vector 中的元素

java - for循环java查询