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

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

你可能感兴趣的:(js基础踩坑手册,javascript,前端,性能优化)