首页 > 解决方案 > 如何正确使用 JS 包括

问题描述

我有以下脚本,我有一个数组,我需要过滤我的特定关键字,在这种情况下GitHub,代码结果为 false,而我需要调整它以返回 true。

我究竟做错了什么?如何解决?

const array1 = ["[GitHub](https://github.com/xxx", 2, 3];

console.log(array1.includes('GitHub'));

标签: javascript

解决方案


正如所评论.includes的那样,这不是预期的功能。它会进行精确搜索,而您正在寻找部分搜索。

array.some + String.includes

正如@Nick Parsons正确指出的那样,由于数字没有.includes,我们必须将其转换为字符串。

只是提醒一下,第一个片段,如果一个数字出现在有效匹配之前,它将引发错误。

const array1 = [5, "[GitHub](https://github.com/xxx", 2, 3];

console.log(array1.some((str) => str.toString().includes('GitHub')));


字符串.includes

如果数组中有原始值,则可以直接使用string.includes

正如@Max所评论的那样

“部分搜索”是一个颇具误导性的术语。按谓词搜索才是真正的

const array1 = ["[GitHub](https://github.com/xxx", 2, 3];

console.log(array1.join().includes('GitHub'));

注意,sytring.includes是一个区分大小写的函数,如果大小写不匹配,将会失败。

如果您希望进行不区分大小写的搜索,请将两个字符串值转换为相同的大小写或使用正则表达式

const array1 = ["[GitHub](https://github.com/xxx", 2, 3];

function test(str) {
  const regex = new RegExp(str, 'i')
  console.log(regex.test(array1.join()));
}

test('GitHub')
test('git')
test('hub')


推荐阅读