当前位置: 首页 > article >正文

js判断字符在不在数组里面的5种方式

在 JavaScript 中,想要判断一个字符是否存在于数组中。

1. 使用 Array.prototype.includes

includes 方法返回一个布尔值,表示数组是否包含指定的元素。

const array = ['a', 'b', 'c', 'd'];
const char = 'b';

if (array.includes(char)) {
  console.log(`${char} 存在于数组中`);
} else {
  console.log(`${char} 不存在于数组中`);
}
2. 使用 Array.prototype.indexOf

indexOf 方法返回指定元素在数组中的索引,如果不存在则返回 -1。

const array = ['a', 'b', 'c', 'd'];
const char = 'b';

if (array.indexOf(char) !== -1) {
  console.log(`${char} 存在于数组中`);
} else {
  console.log(`${char} 不存在于数组中`);
}
3. 使用 Array.prototype.some

some 方法测试数组中是否有至少一个元素通过提供的函数测试。如果有一个元素满足条件,则返回 true,否则返回 false。

const array = ['a', 'b', 'c', 'd'];
const char = 'b';

if (array.some(element => element === char)) {
  console.log(`${char} 存在于数组中`);
} else {
  console.log(`${char} 不存在于数组中`);
}
4. 使用 Set

如果你需要频繁检查元素是否存在,可以考虑使用 Set

const array = ['a', 'b', 'c', 'd'];
const char = 'b';
const set = new Set(array);

if (set.has(char)) {
  console.log(`${char} 存在于数组中`);
} else {
  console.log(`${char} 不存在于数组中`);
}
5. 使用 Array.prototype.find

find 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。

const array = ['a', 'b', 'c', 'd'];
const char = 'b';

if (array.find(element => element === char) !== undefined) {
  console.log(`${char} 存在于数组中`);
} else {
  console.log(`${char} 不存在于数组中`);
}

根据场景,选择适合用的方式


http://www.kler.cn/a/567926.html

相关文章:

  • tableau之雷达图和凹凸图
  • Rohm发布TOLL封装650V GaN HEMT,引领汽车用GaN器件大规模生产新浪潮
  • SOC-ATF 安全启动BL2流程分析(2)
  • Linux 服务器运维常用命令大全
  • 夜天之书 #106 Apache 软件基金会如何投票选举?
  • Redis和MySQL的实时数据同步方案
  • 后台数据报表导出数据量过大问题
  • 嵌入式轻量化SDK设计,EasyRTC音视频通话SDK压缩至500K-800K
  • 云和恩墨亮相PolarDB开发者大会,与阿里云深化数据库服务合作
  • 视频推拉流EasyDSS点播平台云端录像播放异常问题的排查与解决
  • 9. 【.NET 8 实战--孢子记账--从单体到微服务--转向微服务】--微服务基础工具与技术--Ocelot 网关--请求聚合
  • leetcode 73. 矩阵置零
  • 【数据结构】从位图到布隆过滤器
  • 新时代,科技助力运动旅游开启新潮流
  • Android 数据库查询对比(APN案例)
  • 【Django REF】Django REF 常用知识点汇总
  • Qt 自带颜色属性
  • LVS+Keepalived 高可用集群搭建
  • 智能图像处理平台:图片管理
  • MySQL DBA技能指南