我正在检查字符串输入是否包含任何字符串数组。它通过了大部分测试,但未通过以下测试。
任何人都可以破解我的代码,为什么它无法正常工作?
function checkInput(input, words) {
var arr = input.toLowerCase().split(" ");
var i, j;
var matches = 0;
for(i = 0; i < arr.length; i++) {
for(j = 0; j < words.length; j++) {
if(arr[i] == words[j]) {
matches++;
}
}
}
if(matches > 0) {
return true;
} else {
return false;
}
};
checkInput("Visiting new places is fun.", ["aces"]); // returns false // code is passing from this test
checkInput('"Definitely," he said in a matter-of-fact tone.',
["matter", "definitely"])); // returns false; should be returning true;
感谢您的时间!
答案 0 :(得分:3)
您可以使用功能方法。试试Array.some。
const words = ['matters', 'definitely'];
const input = '"Definitely," he said in a matter-of-fact tone.';
console.log(words.some(word => input.includes(word)));
答案 1 :(得分:0)
您可以使用array#includes
检查输入中是否存在单词,并将input
和words
换成小写,然后使用array#includes
。
function checkInput(input, words) {
return words.some(word => input.toLowerCase().includes(word.toLowerCase()));
}
console.log(checkInput('"Definitely," he said in a matter-of-fact tone.',
["matter", "definitely"]));
您可以创建regular expression并使用i
标志来指定不区分大小写
function checkInput(input, words) {
return words.some(word => new RegExp(word, "i").test(input));
}
console.log(checkInput('"Definitely," he said in a matter-of-fact tone.',
["matter", "definitely"]));