4 回答
TA贡献1836条经验 获得超4个赞
您是否处于无法使用的情况Array.prototype.findIndex?(即你必须支持IE)
如果不:
const banLinks = ["hello.com","test.net","this.com"];
const is_banned = banLinks.findIndex(bl => myLink.indexOf(bl) > -1) > -1
并使用您编辑的示例:
const banLinks = ["hello.com","test.net","this.com"];
// is_banned is now a function that ingests a link.
const is_banned = (myLink) => banLinks.findIndex(bl => myLink.indexOf(bl) > -1) > -1
// Get first link from titlesArray that is not banned.
const urllink = titlesArray.map(t => t.link).find(li => is_banned(li) == false)
尽管这都是根据您提供的代码进行的猜测。目前还不清楚你想在 for 循环中做什么。如果要查找第一个有效的(即,未禁止的)urllink,您应该break在找到它后才进行。否则,urllink其余的后续有效值titlesArray将覆盖先前的有效值。
TA贡献1817条经验 获得超14个赞
告别 indexOf() 并使用 ES7 .includes() 来检查某个项目是否在数组内。
我想检查我通过 a.getAttribute("href") 获得的 myLink 是否包含这些单词之一,最好的方法是什么?
if ( banLinks.includes(myLink) ){
urllink = myLink;
}
TA贡献1843条经验 获得超7个赞
你可以试试这个。请看一下
const banLinks = ["hello.com","test.net","this.com"];
var bannedUrlTest = new URL("http://www.hellotest.net");
var safeUrlTest = new URL("http://www.google.net");
var safeUrl = null;
var bannedUrlArray = banLinks.filter((link)=>{
return bannedUrlTest.href.includes(link)
})
if(bannedUrlArray.length < 1){
safeUrl = bannedUrlTest.href;
} else {
console.log('contains banned links')
}
var safeUrlArray = banLinks.filter((link)=>{
return safeUrlTest.href.includes(link)
})
if(safeUrlArray.length < 1){
safeUrl = safeUrlTest.href;
console.log('safeUrl', safeUrl);
}
TA贡献1785条经验 获得超8个赞
<html>
<body>
<ul class="links">
<li>
<a href="hello.com">hello</a>
</li>
<li>
<a href="steve.tech">steve</a>
</li>
<li>
<a href="this.net">this</a>
</li>
<li>
<a href="Nathan.net">Nathan</a>
</li>
</ul>
</body>
<script>
var links=[...document.querySelectorAll(".links a")]; //all links
const BlackListLinks = ["hello.com","test.net","this.com"]; //BlackListLinks
const goodLinks=[]; //stores the links don't in BlackListLinks
for (let i = 0; i < links.length; i++) { //iterate over all links
const link = links[i].getAttribute("href"); //get the current link
if (!BlackListLinks.includes(link)){ //test if the current link don't exist in BlackListLinks
goodLinks.push(link); //add link to the goodLinks
}
}
console.log(goodLinks);//["steve.tech", "this.net", "Nathan.net"]
</script>
</html>
添加回答
举报