其他分享
首页 > 其他分享> > 数组filter,find,map,some,every,reduce的用法简单梳理

数组filter,find,map,some,every,reduce的用法简单梳理

作者:互联网

一、filter

  数组的过滤或筛选功能,根据筛选条件返回一个包含符合条件元素的新数组,不影响原数组,筛选条件写在一个函数中

let arr= [
    {id:1,name: "a", age: 18},
    {id:2,name: "b", age: 15},
    {id:3,name: "c", age: 16},
    {id:4,name: "d", age: 17},
    {id:5,name: "e", age: 19}
]
let newarr=arr.filter(function(item){
    return item.age>15
})
console.log(newarr)
//[ {id: 1, name: "a", age: 18},
{id: 3, name: "c", age: 16},
{id: 4, name: "d", age: 17},
{id: 5, name: "e", age: 19}]

 

二、find

  返回通过函数内条件的第一个元素的

let arr = [1,2,3];
let arr1=arr.find(function (item) {
    return item>=2
});
console.log( arr5); //2

三、map

  数组的映射,返回一个新数组,其值是通过函数处理过的值

 let arr = [2,3,5,6]
    let arr1 = arr.map(function(item){
        return item +1;
    })
    console.log(arr1)//[3,4,6,7]
======================================

let arr = [2,3,5,6,7,8]
    let arr1 = arr.map(function(item){
        return item >5;
    })
    console.log(arr1)//[false,false,false,true,true,true]

 

四、some

  some() 方法会依次执行数组的每个元素:

  如果有一个元素满足条件,则表达式返回true , 剩余的元素不会再执行检测。
  如果没有满足条件的元素,则返回false

let arr = [2, 4, 6, 8];
let flag = arr.some(function(item) {
    return item > 5
});
console.log(flag); //true

五、every

  every()检测数组中的所有元素是否都满足函数的中 的筛选条件

  都满足返回true否则返回false

let arr = [2, 4, 6, 8];
let flag = arr.every(function(item) {
    return item > 6
});
console.log(flag); //false

 

六、reduce

  从左到右累加数组中的值,最后得到的仍是一个值

let arr = [2,3,5,6,7,8,'a']
    let arr1 = arr.reduce(function(val,item,index,origin){
        console.log(val,item,index,origin)//val是累加值,item是当前值,index下标从1开始,arr[0]默认为第一次的累加值,origin是数组本身
        return val+item
    })
    console.log(arr1)// '31a'

 

TRANSLATE with x English
Arabic Hebrew Polish
Bulgarian Hindi Portuguese
Catalan Hmong Daw Romanian
Chinese Simplified Hungarian Russian
Chinese Traditional Indonesian Slovak
Czech Italian Slovenian
Danish Japanese Spanish
Dutch Klingon Swedish
English Korean Thai
Estonian Latvian Turkish
Finnish Lithuanian Ukrainian
French Malay Urdu
German Maltese Vietnamese
Greek Norwegian Welsh
Haitian Creole Persian  
  TRANSLATE with COPY THE URL BELOW Back EMBED THE SNIPPET BELOW IN YOUR SITE Enable collaborative features and customize widget: Bing Webmaster Portal Back

标签:map,arr,name,reduce,age,some,item,let,id
来源: https://www.cnblogs.com/lyj0810/p/16598454.html