将数组传递给include()JavaScript

时间:2019-03-25 04:11:36

标签: javascript

我正在尝试查找一个字符串是否包含多个.includes()存储在数组中的字符串

所以我尝试了

let string = 'hello james';

console.log(string.includes(['hello', 'james']));

但是它以false的形式返回。.当我知道字符串中包含'hello'或'james'时,这甚至可能吗?如何判断一个字符串是否包含单词“ hello”或“ james”

所以在伪代码中,它看起来像string.includes('hello' || 'james');

2 个答案:

答案 0 :(得分:3)

基于docsincludes的第一个参数是字符串而不是数组。

您可以这样做:

如果要检查字符串中是否存在数组中的每个字符串,可以使用everyincludes组合

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)

根据documentationstr.includesstring作为第一个参数。

因此,当您传递数组时,它将字符串数组转换为单个字符串,并将该字符串用作包含函数的第一个参数。

只是为了证明这一点,

let string = "hello,james";
var array = ["hello", "james"]

console.log(string.includes(array)); // returns true, as array would be converted to "hello,james"