我正在尝试查找一个字符串是否包含多个.includes()
存储在数组中的字符串
所以我尝试了
let string = 'hello james';
console.log(string.includes(['hello', 'james']));
但是它以false
的形式返回。.当我知道字符串中包含'hello'或'james'时,这甚至可能吗?如何判断一个字符串是否包含单词“ hello”或“ james”
所以在伪代码中,它看起来像string.includes('hello' || 'james');
答案 0 :(得分:3)
基于docs,includes
的第一个参数是字符串而不是数组。
您可以这样做:
如果要检查字符串中是否存在数组中的每个字符串,可以使用every
和includes
组合
let string = 'hello james';
let toCheck = ['hello', 'james'];
let result = toCheck.every(o => string.includes(o));
console.log(result);
如果要检查字符串中是否存在至少一个条目,可以使用some
代替every
。
let string = 'hello james';
let toCheck = ['hello', 'james1'];
let result = toCheck.some(o => string.includes(o));
console.log(result);
答案 1 :(得分:0)
根据documentation,str.includes
将string
作为第一个参数。
因此,当您传递数组时,它将字符串数组转换为单个字符串,并将该字符串用作包含函数的第一个参数。
只是为了证明这一点,
let string = "hello,james";
var array = ["hello", "james"]
console.log(string.includes(array)); // returns true, as array would be converted to "hello,james"