JS判断数组中是否存在某个值或者某个对象的值

43 篇文章 2 订阅
27 篇文章 0 订阅

一、判断是否存在某个值 

    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);
// expected output: -1

  • 8
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱宇阳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值