前端知识点随记
格式化字符串
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');
}
本文来自博客园,作者:梦回大唐meng,转载请注明原文链接:https://www.cnblogs.com/BitX/p/18304573
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?