我有一个字符串数组,我想用另一个单词数组过滤。 目标是删除包含第二个参数的一个单词的整个字符串。
让我们以此为示例:
comments = [ "Very useful tutorial, thank you so much!",
"React is not a damn framework, it's a LIBRARY"
"Why you put bloody kitten pictures in a tech tutorial is beyond me!",
"Which one is better, React or Angular?",
'There is no "better", it depends on your use case, DAMN YOU'
]
bannedWords = ['bloody', 'damn']
我的代码返回了comments
的完整数组,我不明白如何过滤bannedWords
数组的所有元素。
我可以肯定我在那里缺少基本的东西,但是现在我已经被卡住了一段时间,所以...谢谢!
这是我编写的代码:
return comments.filter(comment => comment.includes(bannedWords) == false)
};
答案 0 :(得分:3)
function filterOffensiveComments(comments, bannedWords) {
return comments.filter(comment => !bannedWords.some(word => comment.includes(word)));
}
.includes
仅接受一个String
。
使用some
而不是every
,因为它会提前返回。
答案 1 :(得分:2)
检查您要遍历的注释中是否不包含.every
个禁止词。确保首先在评论中致电toLowerCase
:
const comments = ["Very useful tutorial, thank you so much!", "React is not a damn framework, it's a LIBRARY",
"Why you put bloody kitten pictures in a tech tutorial is beyond me!", "Which one is better, React or Angular?", 'There is no "better", it depends on your use case, DAMN YOU'];
const bannedWords = ['bloody', 'damn'];
const result = comments.filter(comment => bannedWords.every(word => !comment.toLowerCase().includes(word)))
console.log(result);
或者,如果您想构造一个正则表达式:
const comments = ["Very useful tutorial, thank you so much!", "React is not a damn framework, it's a LIBRARY",
"Why you put bloody kitten pictures in a tech tutorial is beyond me!", "Which one is better, React or Angular?", 'There is no "better", it depends on your use case, DAMN YOU'];
const bannedWords = ['bloody', 'damn'];
const re = new RegExp(bannedWords.join('|'), 'i');
const result = comments.filter(comment => !re.test(comment));
console.log(result);
答案 2 :(得分:0)
function filterOffensiveComments(comments, bannedWords) {
return comments.filter(item=>{
let shouldDelete = false;
bannedWords.forEach(word=>{
if(item.includes(word)){
shouldDelete = true;
}
})
if(shouldDelete){
return null
}
return item;
})
};
答案 3 :(得分:0)
试图使用回调实现-
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset >
<legend>want car?</legend>
<input id="k" type="radio" name="car9" /> <label for="m">yes </label>
<input type="radio" name="car9" value="No" />No
<nav id="n">
<ul>
<div class="ok" style="display:none">
<table>
<tbody>
<tr>
<th></th>
<th>Prod</th>
<th>Price $</th>
</tr>
<tr>
<td><input class="ok" name="car10" type="checkbox" /></td>
<td>car</td>
<td><input class="form-control input-sm" name="txtCostAmount80" value="380" type="text" readonly="" /></td>
</tr>
</tbody>
</table>
</div>
</ul>
</nav>
</fieldset>