如何检查字符串是否包含数组的任何元素?如果元素有一些字符串,我想过滤一些数组。请参阅下面的代码。
var arr = ['banana', 'monkey banana', 'apple', 'kiwi', 'orange'];
function checker(value) {
var prohibited = ['banana', 'apple'];
for (var i = 0; i < prohibited.length; i++) {
if (value.indexOf(prohibited[i]) == -1) {
return true;
} else {
return false;
}
}
}
arr = arr.filter(checker);
console.log(arr);
结果是[ 'apple', 'kiwi', 'orange' ]
。 'apple'
应该被删除,但事实并非如此。
上面的代码只过滤了“香蕉”,没有过滤“苹果”。我有很多关键词需要过滤。有没有更简单的方法?
最佳答案
它可以这么简单:
const arr = ['banana', 'monkey banana', 'apple', 'kiwi', 'orange'];
const checker = value =>
!['banana', 'apple'].some(element => value.includes(element));
console.log(arr.filter(checker));
ECMAScript 6 FTW!
检查器
使用an arrow function .
!
表示它将排除所有不满足条件的元素。
The
some()
method tests whether some element in the array passes the test implemented by the provided function.
<子>来自Array.prototype.some()
docs on MDM
The
includes()
method determines whether one string may be found within another string, returningtrue
orfalse
as appropriate.
<子>来自String.prototype.includes()
docs on MDM
由于并非所有浏览器都支持某些最新的 ECMAScript 功能,因此您应该使用 Babel将您的代码编译为 ECMAScript 5。
关于javascript - 在 JavaScript 中检查字符串是否包含数组的任何元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37428338/