数组 every some filter find findIndex reduce的方法

239 阅读2分钟

个人这个用的比较多,来个三元判断特别好用。比方说:一个实例列表,根据他的状态State来判断某一条的数据是否是可以点击状态。

var potatos = [
    { id: '1001', weight: 50 }, 
    { id: '1002', weight: 80 }, 
    { id: '1003', weight: 120 }, 
    { id: '1004', weight: 40 }, 
    { id: '1005', weight: 110 }, 
    { id: '1006', weight: 60 }
]

map和forEach加上return map有返回值 forEach返回undefined

1. every 全符合

var allbig = potatos.every(potato => { return potato.weight > 100 }) 
//false

2. 筛选过滤 filter 返回一个新的对象数组,并不会改变原数组

var bigOnes = potatos.filter(potato => { return potato.weight > 100 }) 
// [ { id: '1003', weight: 120 }, { id: '1005', weight: 110 } ]

3. some 有符合 当只需要判断数组中有没有符合条件的时候(一个就行)

 var hasbig = potatos.some(potato => { return potato.weight > 100 })
 //true

4. find 返回一个符合的

var big = potatos.find(potato => { return potato.weight > 100 })    
//{ id: '1003', weight: 120 }

findsome很类似,都是寻找符合条件的,有一个就可以 不过some进去搜罗了一圈回来报了个“有”(true),而find则把那个数据拿出来(返回第一个符合条件的对象)

5. 返回序号 findIndex

var i = potatos.findIndex(potato=>{ return potato.weight > 100 })
//2

当需要知道所需元素的索引,就可以用findIndex

findIndex返回第一个符合条件的索引号

6.递归累加 reduce

var sum = weight.reduce((sum, w) => { return w + sum },0) 
//460 
//并不会改变原表格
reduce()方法接收一个回调函数作为第一个参数,回调函数又接受四个参数,分别是;\
1、previousValue =>初始值或上一次回调函数叠加的值;\
2、currentValue => 本次回调(循环)将要执行的值;\
3、index=>“currentValue”的索引值;\
4、arr => 数组本身;\
reduce()方法返回的是最后一次调用回调函数的返回值;