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} 不存在于数组中`);
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值