前端知识点随记

格式化字符串

let temp;
temp=2;
let str=`${temp}期产品存在问题`;

判断数组中是否存在某值

使用 indexOf()

indexOf() 方法返回数组中找到的第一个匹配项的索引,如果没有找到,则返回 -1。

const array = [1, 2, 3, 4, 5];
const valueToFind = 3;

if (array.indexOf(valueToFind) !== -1) {
  console.log('Value found');
} else {
  console.log('Value not found');
}

使用 includes()

includes() 方法检查数组中是否存在某个值,如果存在则返回 true,否则返回 false。

Es6+环境

const array = [1, 2, 3, 4, 5];
const valueToFind = 3;

if (array.includes(valueToFind)) {
  console.log('Value found');
} else {
  console.log('Value not found');
}

使用 some()

some() 方法测试数组中是否至少有一个元素通过了被提供的函数的测试。如果有任何元素通过测试,则表达式返回 true;如果没有,则返回 false。

const array = [1, 2, 3, 4, 5];
const valueToFind = 3;

if (array.some(element => element === valueToFind)) {
  console.log('Value found');
} else {
  console.log('Value not found');
}

使用 find()

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

const array = [1, 2, 3, 4, 5];
const valueToFind = 3;

const foundValue = array.find(element => element === valueToFind);

if (foundValue !== undefined) {
  console.log('Value found');
} else {
  console.log('Value not found');
}

使用 filter()

虽然 filter() 主要用于创建一个新数组,但它也可以用来检查数组中是否存在某个值。

const array = [1, 2, 3, 4, 5];
const valueToFind = 3;

const filteredArray = array.filter(element => element === valueToFind);

if (filteredArray.length > 0) {
  console.log('Value found');
} else {
  console.log('Value not found');
}
posted @   梦回大唐meng  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示