前端知识点随记
格式化字符串
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

浙公网安备 33010602011771号