我有以下简单的代码:
var S = require('string');
function matchBlacklist(inputString) {
var blacklist = ["facebook", "wikipedia", "search.ch", "local.ch"];
var found = false;
for (var i = 0; i < blacklist.length; i++) {
if (S(inputString).contains(blacklist[i]) > -1) {
found = true;
}
}
return (found);
}
matchBlacklist("www.facebook.com/this_is_a_test"); // returns true
matchBlacklist("www.example.com/this_is_a_test"); // returns true
但它总是回归真实;因为它应该为第二种情况返回false
答案 0 :(得分:4)
您应该测试if(string.includes(substring)){ ... }
而不是if(string.includes(substring) > -1 ){ ... }
但这是一个更优雅的单行:
const blacklist = ["facebook", "wikipedia", "search.ch", "local.ch"];
const matchBlacklist = inputString => blacklist.some(word => inputString.includes(word))
console.log( matchBlacklist("www.facebook.com/this_is_a_test") ); // returns true
console.log( matchBlacklist("www.example.com/this_is_a_test") ); // returns false
答案 1 :(得分:2)
使用数组find
方法的更好方法,如果表达式求值true
否则返回元素,则返回基于查找结果的布尔值
function matchBlacklist(inputString) {
var blacklist = ["facebook", "wikipedia", "search.ch", "local.ch"];
return !!blacklist.find(b => inputString.includes(b))
}
console.log(matchBlacklist("www.facebook.com/this_is_a_test"));
console.log(matchBlacklist("www.example.com/this_is_a_test"));
答案 2 :(得分:0)
您可以使用“indexOf”代替“contains”方法。 “contains”方法将返回布尔值,因此您无法将布尔值与数字进行比较。 “indexOf”将返回字符串的索引号,因此您可以在此处进行比较。
var S = require('string');
function matchBlacklist(inputString) {
var blacklist = ["facebook", "wikipedia", "search.ch", "local.ch"];
var found = false;
for (var i = 0; i < blacklist.length; i++) {
if (S(inputString).indexOf(blacklist[i]) > -1) {
found = true;
}
}
return (found);
}
matchBlacklist("www.facebook.com/this_is_a_test"); // returns true
matchBlacklist("www.example.com/this_is_a_test"); // returns truetes