有一个数组,我想搜索包含'john'(这四个字母)的名字。
bool 值将返回 true。
const dragons = ['Tim', 'Johnathan', 'Sandy', 'Sarah'];
我在 JS 中尝试过的:
dragons.includes('John');
这会返回 false。
我应该如何使用 include 来缓存它?
最佳答案
您应该改用 .some
,并使用 startsWith
检查数组中是否有任何项目以 'John'
开头:
const dragons = ['Tim', 'Johnathan', 'Sandy', 'Sarah'];
const anyJohn = dragons.some((name) => name.startsWith('John'));
console.log(anyJohn);
如果 John
可以在字符串中的任何地方(看起来有点奇怪),那么使用 .includes
:
const dragons = ['Tim', 'Johnathan', 'Sandy', 'Sarah'];
const anyJohn = dragons.some((name) => name.includes('John'));
console.log(anyJohn);
关于javascript - 检查此数组是否包含其中包含 "John"的任何名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54612742/