some、every、find、findIndex、reduce的用法
前言
从最开始学的for循环遍历方法,到后来层出不穷的各种遍历方法,其实最大的区别就是应用场景的不同。 我们最需要记住的就是,什么情况下用哪一种方法比较合适。。
数组数据
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 }]
提示:以下是本篇文章正文内容,下面案例可供参考
some
var hasbig = potatos.some(potato => { return potato.weight > 100 })
//true
我们的some小伙计,只要找到一个符合条件的,就回来报告true 所以并不会全部遍历,不做多余的活(性能优良),返回结果是布尔类型。
every
var allbig = potatos.every(potato => { return potato.weight > 100 })
//false
遍历每一个元素,发现有不满足条件的元素就返回false,如果都遍历完后还未找到不满足条件的元素,则全部符合条件,返回true
find
var big = potatos.find(potato => { return potato.weight > 100 })
//{ id: '1003', weight: 120 }
find和some很类似,都是寻找符合条件的,有一个就可以 不过some进去搜罗了一圈回来报了个“有”(true),而find则把那个数据整个返回出来(返回第一个符合条件的对象)
findIndex
var i = potatos.findIndex(potato=>{ return potato.weight > 100 })
//2
find 的孪生兄弟,不过find返回的是数据,而find返回的是该主句的索引值
总结
遍历数据,查询符合条件的数据,不过易混淆
本文参考:https://juejin.cn/post/6844903870154588168