只是想知道,是否有一种方法可以向.includes方法添加多个条件,例如:
var value = str.includes("hello", "hi", "howdy");
想象一下逗号表示“或”。
它现在询问字符串是否包含hello, hi或howdy。所以只有当其中一个条件为真。
有什么方法可以做到吗?
只是想知道,是否有一种方法可以向.includes方法添加多个条件,例如:
var value = str.includes("hello", "hi", "howdy");
想象一下逗号表示“或”。
它现在询问字符串是否包含hello, hi或howdy。所以只有当其中一个条件为真。
有什么方法可以做到吗?
当前回答
const givenArray = ['Hi, how are you', 'how are you', 'howdy, how you doing'] const includeValues = ["hello", "hi", "howdy"] const filteredStrArray = givenArray。filter(str => includeValues)str.toLowerCase().includes(value))) console.log (filteredStrArray);
其他回答
即使有且只有一个条件为真,它也能工作:
var str = "bonjour le monde vive le javascript";
var arr = ['bonjour','europe', 'c++'];
function contains(target, pattern){
var value = 0;
pattern.forEach(function(word){
value = value + target.includes(word);
});
return (value === 1)
}
console.log(contains(str, arr));
那么['hello', 'hi', 'howdy'].includes(str)呢?
不是最好的答案,也不是最干净的答案,但我认为它更宽容。 比如,如果你想对所有的支票使用相同的过滤器。 实际上.filter()与数组一起工作并返回一个过滤后的数组(我发现这也更容易使用)。
var str1 = 'hi, how do you do?';
var str2 = 'regular string';
var conditions = ["hello", "hi", "howdy"];
// Solve the problem
var res1 = [str1].filter(data => data.includes(conditions[0]) || data.includes(conditions[1]) || data.includes(conditions[2]));
var res2 = [str2].filter(data => data.includes(conditions[0]) || data.includes(conditions[1]) || data.includes(conditions[2]));
console.log(res1); // ["hi, how do you do?"]
console.log(res2); // []
// More useful in this case
var text = [str1, str2, "hello world"];
// Apply some filters on data
var res3 = text.filter(data => data.includes(conditions[0]) && data.includes(conditions[2]));
// You may use again the same filters for a different check
var res4 = text.filter(data => data.includes(conditions[0]) || data.includes(conditions[1]));
console.log(res3); // []
console.log(res4); // ["hi, how do you do?", "hello world"]
扩展字符串本机原型:
if (!String.prototype.contains) {
Object.defineProperty(String.prototype, 'contains', {
value(patterns) {
if (!Array.isArray(patterns)) {
return false;
}
let value = 0;
for (let i = 0; i < patterns.length; i++) {
const pattern = patterns[i];
value = value + this.includes(pattern);
}
return (value === 1);
}
});
}
允许你做以下事情:
console.log('Hi, hope you like this option'.toLowerCase().contains(["hello", "hi", "howdy"])); // True
这取决于你在什么上下文中使用它。 我在一个对象上使用它来检查是否有任何键有一个空字符串或null作为它的值,它工作
Object.values(object).includes('' || null)