javascript - 如何正确使用 JS 包括
问题描述
我有以下脚本,我有一个数组,我需要过滤我的特定关键字,在这种情况下GitHub
,代码结果为 false,而我需要调整它以返回 true。
我究竟做错了什么?如何解决?
const array1 = ["[GitHub](https://github.com/xxx", 2, 3];
console.log(array1.includes('GitHub'));
解决方案
正如所评论.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
“部分搜索”是一个颇具误导性的术语。按谓词搜索才是真正的
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')
推荐阅读
- html - 需要帮助格式化 YouTube SAMI(.smi) 字幕
- javascript - React Typescript 和内联 if 语句来建立类型
- python - Scrapy 爬取规则发送 URL
- vue.js - Vuex:如何在调度之前检查一个动作是否存在?
- eclipse - Scala Eclipse IDE 不会通过 Gradle 引入外部依赖项
- c++ - 对我所有函数的未定义引用 C++ 我认为这可能是因为我的 makefile
- mongodb - MongoDB $in 内 $cond
- python - 在 Django 中搜索期间分页不起作用
- jquery - 在两列布局中切换特定列?
- android - 如何清除/删除 Webview 的 Web 存储