我正在尝试使用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/