zoukankan      html  css  js  c++  java
  • 其他01filter、find、findIndex、map

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

    1.以下代码在myArr数组中查找元素值大于5的元素,找到后立即返回。返回的结果为查找到的元素:
      const myArr=[1,2,3,4,5,6];
      var v=myArr.find(value=>value>4);
      console.log(v);// 6
    
    2.没有符合元素,返回undefined:
      const myArr=[1,2,3,4,5,6];
      var v=myArr.find(value=>value>40);
      console.log(v);// undefined

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

    const bookArr=[
        {
            id:1,
            name:"小张"
        },
        {
            id:2,
            name:"小李"
        },
        {
            id:3,
            name:"小红"
        },
        {
            id:4,
            name:"小王"
        }
    ];
    var i=bookArr.findIndex((value)=>value.id==4);
    console.log(i);// 3
    var i2=bookArr.findIndex((value)=>value.id==100);
    console.log(i2);// -1
    特殊例子:
    let index=this.bookArr.findIndex(d=>d.id>=3)
    
    

    03.filter:filter()与find()使用方法也相同。同样都接收三个参数。不同的地方在于返回值。filter()返回的是数组,数组内是所有满足条件的元素,而find()只返回第一个满足条件的元素。如果条件不满足,filter()返回的是一个空数组,而find()返回的是undefined,通俗讲:filter函数, 过滤通过条件的元素组成一个新数组, 原数组不变

    var userArr = [
        { id:1,name:"xiaoqiang"},
        { id:2,name:"xiaohong" },
        { id:3,name:"xiaohua" },
    ]
    console.log(userArr.filter(item=>item.id>1));
    //[ { id: 2, name: 'xiaohong' },{ id: 3, name: 'xiaohua' } ]

    04.map:map函数,遍历数组每个元素,并回调操作,需要返回值,返回值组成新的数组,原数组不变

    let array = [1, 2, 3, 4, 5];
    
    let newArray = array.map((item) => {
        return item * item;
    })
    
    console.log(newArray)  // [1, 4, 9, 16, 25]

    05.some函数,遍历数组中是否有符合条件的元素,返回Boolean值

     06.every函数, 遍历数组中是否每个元素都符合条件, 返回Boolean值

     07.forEach循环,循环数组中每一个元素并采取操作, 没有返回值, 可以不用知道数组长度

  • 相关阅读:
    httpcontext in asp.net unit test
    initialize or clean up your unittest within .net unit test
    Load a script file in sencha, supports both asynchronous and synchronous approaches
    classes system in sencha touch
    ASP.NET MVC got 405 error on HTTP DELETE request
    how to run demo city bars using sencha architect
    sencha touch mvc
    sencha touch json store
    sencha touch jsonp
    51Nod 1344:走格子(贪心)
  • 原文地址:https://www.cnblogs.com/hunter1/p/15717766.html
Copyright © 2011-2022 走看看