函数keywordusage
应该以布尔数组的形式返回文本中存在哪些关键字,如:array: [true, false, false]
。基于函数的第二个参数。现在,我只能返回true
值,当案例为false时,我不知道如何返回false
值。代码如下。输出应为 [true,false,false]
{function keywordusage(str,strArr){
var count = [];
var found = true;
var notfound = false;
var words = str.split(' ');
var wordsLength = words.length;
var ArrLength = strArr.length;
for(var i = 0; i < ArrLength; i++){
for(var j = 0; j < wordsLength; j++){
if(words[j]===strArr[i])
count.push(true);
}
}
return count;
}
document.write(keywordusage('Dive Into Python is a free book for experienced programmers', ['Python', 'python', 'scala']));}
答案 0 :(得分:1)
您可以使用地图检查模式数组中的单词是否在字符串中:
var keywordusage = (str, strArr) => strArr.map(x => str.split(" ").indexOf(x) !== -1);
console.log(keywordusage('Dive Into Python is a free book for experienced programmers', ['Python', 'python', 'scala']));
&#13;
答案 1 :(得分:0)
您只需要使用array.map()函数,该函数本质上是一个命令,允许您通过对现有数组中的每个值执行函数来创建新数组。
在这种情况下,array1已经存在,并且returnArray未定义
然后我们调用returnArray
等于“通过检查textString.indexOf(array1)
是否大于-1来映射array1中的每个值
.indexOf()
返回字符串中字符串的位置,如果该字符串不存在,则返回-1。
function keywordusage(array1, textString) {
var returnArray = array1.map(x => textString.indexOf(x) > -1);
return returnArray;
}
// demonstration of usage
var checkArray = ["the", "quick", "brown"];
var checkString = "the quick red fox jumped over the lazy dog";
console.log(JSON.stringify(keywordusage(checkArray, checkString)));
答案 2 :(得分:0)
您只需使用javascript map function。
结帐以下代码
function keywordusage(str, strArr) {
var count = [];
strArr.map(function(s) {
return count.push(str.indexOf(s) !== -1);
});
console.log(count);
return count;
}
document.write(keywordusage('Dive Into Python is a free book for experienced programmers', ['Python', 'python', 'scala']));
&#13;
希望这对你有帮助。
答案 3 :(得分:0)
function keywordusage(text, keywords) {
var elements = text.split(" ");
var result = Array();
for (var i=0; i < keywords.length;i++){
if (elements.indexOf(keywords[i]) >= 0)
result[i] = true;
else
result[i] = false;
}//end of for loop
return result;
}
var result = keywordusage('Dive Into Python is a free book for experienced programmers', ['Python', 'python', 'scala']);
console.log(result)