函数 map reduce filter

朴灿烈づ我的快乐病毒、 2022-12-02 04:20 281阅读 0赞

函数 map reduce filter

  1. <script>
  2. var array = [
  3. {
  4. age: 11, name: 'aaa'
  5. },
  6. {
  7. age: 22, name: 'bbb'
  8. },
  9. {
  10. age: 33, name: 'ccc'
  11. }
  12. ];
  13. /* map方法接收一个匿名函数为参数,这个匿名函数又有三个参数 参数一:每个item项 参数二:数组的索引 参数三:调用map方法的数组本身,也就是数组array */
  14. var map = array.map(item => item.age);
  15. console.log(map) // [11,22,33]
  16. /* reduce方法 有两个参数 参数一:回调方法 参数二:累计的初始值 计算过程: 0 + 11 = 11 11 + 22 = 33 33 + 33 = 结果 66 循环的是回调方法,数组中的每个成员都进入回调,但区别在于每次回调方法返回的值,都会传递到下次回调中 =》累加求和 */
  17. var reduce = array.reduce((n, item) => n + item.age, 0)
  18. console.log(reduce) // 66
  19. /* filter方法 用于过滤数据 返回一个数组 filter方法接收一个匿名函数,参数就是数组中的item项, 例如:从上面数据中过滤一个name为ccc的数据 只要filter方法的回调函数中的比较运算符的结果为true, 那么符合条件的对象就会被包在一个数组返回,比较结果为false的就被过滤掉了 */
  20. var filter = array.filter(item => item.name === 'ccc')
  21. console.log(filter) // [{age: 33, name: "ccc"}]
  22. </script>

map

如果需要一个数组,使用map()方法

reduce

如果需要一个结果,使用reduce()方法

filter

如果需要过滤出一个结果,使用filter()方法

发表评论

表情:
评论列表 (有 0 条评论,281人围观)

还没有评论,来说两句吧...

相关阅读