zoukankan      html  css  js  c++  java
  • es6数组方法find()、findIndex()与filter()

    find()

    该方法主要应用于查找第一个符合条件的数组元素。它的参数是一个回调函数。在回调函数中可以写你要查找元素的条件,当条件成立为true时,返回该元素。如果没有符合条件的元素,返回值为undefined。

    以下代码在myArr数组中查找元素值大于4的元素,找到后立即返回。返回的结果为查找到的元素:

    const myArr=[1,2,3,4,5,6];
    let person = myArr.find ( value => value > 4 );
    console.log(person );// 5

    没有符合元素,返回undefined:

    const myArr=[1,2,3,4];
    let person = myArr.find ( value => value > 4 );
    console.log(person );// 5
    回调函数有三个参数。value:当前的数组元素。index:当前索引值。arr:被查找的数组。

    查找索引值为4的元素:

    const myArr=[1,2,3,4,5,6];
    let person = myArr.find ( (value,index,arr) => {
         return index == 4
    } );
    console.log(person );

    findIndex()

    findIndex()与find()的使用方法相同,只是当条件为true时findIndex()返回的是索引值,而find()返回的是元素。如果没有符合条件元素时findIndex()返回的是-1,而find()返回的是undefined。findIndex()当中的回调函数也是接收三个参数,与find()相同。

    const bookArr=[
        {
            id:1,
            bookName:"三国演义"
        },
        {
            id:2,
            bookName:"水浒传"
        },
        {
            id:3,
            bookName:"红楼梦"
        },
        {
            id:4,
            bookName:"西游记"
        }
    ];
    let a = bookArr.findIndex((value)=>value.id==4);
    console.log(a);// 3
    let b = bookArr.findIndex((value)=>value.id==100);
    console.log(b);// -1

    filter()

    filter()与find()使用方法也相同。同样都接收三个参数。不同的地方在于返回值。filter()返回的是数组,数组内是所有满足条件的元素,而find()只返回第一个满足条件的元素。如果条件不满足,filter()返回的是一个空数组,而find()返回的是undefined

    var userArr = [
        { id:1,userName:"laozhang"},
        { id:2,userName:"laowang" },
        { id:3,userName:"laoliu" },
    ]
    console.log(userArr.filter(item=>item.id>1));
    //[ { id: 2, userName: 'laowang' },{ id: 3, userName: 'laoliu' } ]

    数组去重:

    var myArr = [1,3,4,5,6,3,7,4];
    console.log(myArr.filter((value,index,arr)=>arr.indexOf(value)===index));//[ 1, 3, 4, 5, 6, 7 ]
  • 相关阅读:
    Ant 中作用代理
    linux通用自动清理日志脚本
    linux shell 脚本攻略 下
    我在写shell自动部署脚本碰到的问题
    linux shell 脚本攻略(上)
    Java Object.wait() jvm的bug
    shell 脚本 更新或者添加host ,并且增加hostname映射到hosts (修改)
    记一次子域名IP搜集reconngkali
    ie6下面试用png使用滤镜需知
    canvas 使用 图片 切片的时候 在chrome 下 要注意的 一点
  • 原文地址:https://www.cnblogs.com/Essaycode/p/13379561.html
Copyright © 2011-2022 走看看