gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:27:22 24 4
gpt4 key购买 nike

有一个数组,我想搜索包含'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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com