只是想知道,是否有一种方法可以向.includes方法添加多个条件,例如:
var value = str.includes("hello", "hi", "howdy");
想象一下逗号表示“或”。
它现在询问字符串是否包含hello, hi或howdy。所以只有当其中一个条件为真。
有什么方法可以做到吗?
只是想知道,是否有一种方法可以向.includes方法添加多个条件,例如:
var value = str.includes("hello", "hi", "howdy");
想象一下逗号表示“或”。
它现在询问字符串是否包含hello, hi或howdy。所以只有当其中一个条件为真。
有什么方法可以做到吗?
当前回答
(错误答案,不要抄)
其他回答
另一个!
let result const givenStr = 'A, X' //values separated by comma or space. const allowed = ['A', 'B'] const given = givenStr.split(/[\s,]+/).filter(v => v) console.log('given (array):', given) // given contains none or only allowed values: result = given.reduce((acc, val) => { return acc && allowed.includes(val) }, true) console.log('given contains none or only allowed values:', result) // given contains at least one allowed value: result = given.reduce((acc, val) => { return acc || allowed.includes(val) }, false) console.log('given contains at least one allowed value:', result)
即使有且只有一个条件为真,它也能工作:
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));
Def一个旧线程,但仍然得到更新的回复。 我在结果中没有看到它,它是使用.includes在一个字符串中同时搜索多个内容的最简单方法之一。 根据你想要用它做什么,只需运行一个for循环,该循环通过你想要使用.includes检查字符串的项目数组。
Const text = ' does this include item3? ';
For(i = 0; i < arr.length; i++)
{if (text.includes(arr[i])){/* do whatever */ } }
如果字符串中有这些项,它将返回true,然后你可以让它做任何事情。执行一个函数,改变一个变量等等……您还可以在if语句中添加如果它为false时该做什么。
值得注意的是,它将为列表中的每一项执行返回true的代码,因此请确保在您想要执行的代码中对其进行补偿。
编辑-你也可以把它转换成一个函数,设置它来传递参数,这些参数是你检查字符串是否包含的多个东西,只是让它返回true或false,你可以在函数之外对这些信息做任何事情。
1线路方案:
字符串/ Array.prototype。包括('hello' || 'hi' || 'howdy');
let words = 'cucumber, mercy, introduction, shot, howdy'
words.includes('hi' || 'howdy' || 'hello') // true
words.includes('hi' || 'hello') // false
这是一个有争议的选择:
String.prototype.includesOneOf = function(arrayOfStrings) {
if(!Array.isArray(arrayOfStrings)) {
throw new Error('includesOneOf only accepts an array')
}
return arrayOfStrings.some(str => this.includes(str))
}
允许你做以下事情:
'Hi, hope you like this option'.toLowerCase().includesOneOf(["hello", "hi", "howdy"]) // True