JavaScript查找数组内的元素的方法 filter() find includes findIndex lastIndexOf indexOf

需求:查找数组内元素6是否存在
let arr = [1, 3, 6, 5, 7, 6];

方法1、indexOf方法

let index1 = arr.indexOf(6);
console.log(index1);//2

方法2、lastIndexOf方法

从右至左查找,找到返回索引,找不到返回-1

  let index2 = arr.lastIndexOf(6);
 console.log(index2);//5

方法3、includes方法

从左往右查找,找到返回true,找不到返回false

 let resulr = arr.includes(6);
console.log(resulr);//true

方法4、数组专用方法findIndex

findIndex方法:定制版的indexOf,找到返回索引,找不到返回-1

let index3 = arr.findIndex(function (currentValue, currentIndex, currentArray) {
            if (currentValue === 6){
                return true;
            }
        });
console.log(index3);//2

方法5、数组专用方法find

find方法:返回找到的元素值,找不到返回undefined

let arr1 = [1, 2, 3, 4, 5];
let num = arr1.find(item => item > 1);
console.log(num)  //輸出的結果是2

 var arr = [{
        id: 1,
        name: '张一',
        age: 25,
        class: '一班'
    }, {
        id: 1,
        name: '张二',
        age: 25,
        class: '二班'
    }, {
        id: 2,
        name: '张三',
        age: 25,
        class: '三班'
    }]
    let obj = arr.find(item => item.id == 1)
    console.log(obj); 
    // 结果:{id: 1, name: '张一', age: 25, class: '一班'}

方法6、filter()

我们可以使用 Array.filter() 方法在数组中查找满足特定条件的元素。

例如,如果我们要获取大于10的数字数组中的所有项目,则可以执行以下操作:

const array = [10, 11, 3, 20, 5];
 
const greaterThanTen = array.filter(element => element > 10);
 
console.log(greaterThanTen) //[11, 20]
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

都挺好,刚刚好

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

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

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

打赏作者

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

抵扣说明:

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

余额充值