、判断是否存在某个值
1、Array.prototype.indexOf()
indexOf()方法返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
// expected output: 1
// start from index 2
console.log(beasts.indexOf('bison', 2));
// expected output: 4
console.log(beasts.indexOf('giraffe'));
// expected output: -1
2、Array.prototype.includes()
includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回 false。
const array1 = [1, 2, 3];
console.log(array1.includes(2));
// expected output: true
const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat'));
// expected output: true
console.log(pets.includes('at'));
// expected output: false
3、Array.prototype.find()
find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
// expected output: 12
4、Array.prototype.findIndex()
findIndex()方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回-1。
const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber));
// expected output: 3
二、判断是否存在对象的某个值
1、Array.prototype.find() 同上3
const arr = [{id:1, name:'name1'}, {id:2, name:'name2'}, {id:3, name:'name3'}];
const res = arr.find((ev) => {
return ev.id === 3;
});
console.log(res);
// expected output: { id: 3, name: "name3" }
const ret = arr.find((ev) => {
return ev.id === 4;
});
console.log(ret);
// expected output: undefined
2、Array.prototype.findIndex() 同上4
const arr = [{id:1, name:'name1'}, {id:2, name:'name2'}, {id:3, name:'name3'}];
const res = arr.findIndex((ev) => {
return ev.id === 3;
});
console.log(res);
// expected output: 2
const ret = arr.findIndex((ev) => {
return ev.id === 4;
});
console.log(ret);
————————————————
版权声明:本文为CSDN博主「deardanyang」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_34707272/article/details/121919043