检查此数组是否包含其中包含"John"的任何名称

Jac*_*cky 2 javascript

有一个数组,我想搜索有'john'(这四个字母)的名字.

布尔值将返回true.

const dragons = ['Tim', 'Johnathan', 'Sandy', 'Sarah'];
Run Code Online (Sandbox Code Playgroud)

我在JS中尝试过的:

dragons.includes('John');
Run Code Online (Sandbox Code Playgroud)

这返回false.

我该怎么用include来缓存呢?

Cer*_*nce 6

您应该使用.some,并使用startsWith检查数组中的任何项目是否以'John':

const dragons = ['Tim', 'Johnathan', 'Sandy', 'Sarah'];
const anyJohn = dragons.some((name) => name.startsWith('John'));
console.log(anyJohn);
Run Code Online (Sandbox Code Playgroud)

如果John可以在字符串中的任何位置(看起来有点奇怪),那么改为使用.includes:

const dragons = ['Tim', 'Johnathan', 'Sandy', 'Sarah'];
const anyJohn = dragons.some((name) => name.includes('John'));
console.log(anyJohn);
Run Code Online (Sandbox Code Playgroud)