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>
添加回答
舉報