海纳百川,有容乃大

定义:

reduce()方法接受一个函数作为累加器,数组中的每个值(从左向右)开始缩减,最终计算为一个值。对空数组是不会执行回调函数的。

案例:

  1. 计算数组总和:

    var num = [1,2,3,4,5];
    var res = num.reduce(function(total,num){
    return total+num;
    //return total + Math.round(num);//对数组元素四舍五入并计算总和
    },0);
    console.log(res);//
    //num.reduce((total,num) => total += num, 0);
    //没有初始值initialValue(即上面例子中的0),当数组为0时会抛出异常提示reduce函数没有初始值,所以为兼容性一般加上initialValue
  2. 合并二维数组
    var red = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
    return a.concat(b);
    }, []);
    console.log(red)
    VM291:4 (6) [0, 1, 2, 3, 4, 5]
  3. 统计一个数组中有多少个不重复的单词
    不用reduce时:
    var arr = ["apple","orange","apple","orange","pear","orange"];
    function getWordCnt(){
    var obj = {};
    for(var i= 0, l = arr.length; i< l; i++){
    var item = arr[i];
    obj[item] = (obj[item] +1 ) || 1;
    }
    return obj;
    }
    console.log(getWordCnt());
    VM3704:14 {apple: 2, orange: 3, pear: 1} 用reduce时:
    var arr = ["apple","orange","apple","orange","pear","orange"];
    function getWordCnt(){
    return arr.reduce(function(prev,next){
    prev[next] = (prev[next] + 1) || 1;
    return prev;
    },{});
    }
    console.log(getWordCnt());
    VM3704:14 {apple: 2, orange: 3, pear: 1}

理解:

reduce(callback,initialValue)会传入两个参数,回调函数(callback)和初始值(initialValue)。当没有传入初始值时,prev是从数组中第一个元素开始的,next是数组的第二个元素;当传入初始值(initialValue)后,第一个prev将是initialValue,next将是数组中的第一个元素。

例如:

var arr = ["apple","orange"];
function noPassValue(){
return arr.reduce(function(prev,next){
console.log("prev:",prev);
console.log("next:",next);
return prev;
});
} function passValue(){
return arr.reduce(function(prev,next){
console.log("prev:",prev);
console.log("next:",next);
prev[next] = 1;
return prev;
},{});
}
console.log("No Additional parameter:",noPassValue());
console.log("----------------");
console.log("With {} as an additional parameter:",passValue());

运行结果为:

文章转载自:https://www.cnblogs.com/mafeng/p/10249887.html

JS中的reduce函数的更多相关文章

  1. js中的reduce()函数

    1. 首先看下语法如下 2 . 写了个demo如下 var fa = [1,2,3,4] function red(a, b) { console.log(arguments); return a + ...

  2. js中的回调函数的理解和使用方法

    js中的回调函数的理解和使用方法 一. 回调函数的作用 js代码会至上而下一条线执行下去,但是有时候我们需要等到一个操作结束之后再进行下一个操作,这时候就需要用到回调函数. 二. 回调函数的解释 因为 ...

  3. underscore.js中的节流函数debounce及trottle

    函数节流   throttle and debounce的相关总结及想法 一开始函数节流的使用场景是:放止一个按钮多次点击多次触发一个功能函数,所以做了一个clearTimeout setTimeou ...

  4. js中如何在一个函数里面执行另一个函数

    1.js中如何在函数a里面执行函数b function a(参数c){ b(); } function b(参数c){ } 方法2: <script type="text/javasc ...

  5. JavaScript -- 时光流逝(七):js中的全局函数

    JavaScript -- 知识点回顾篇(七):js中的全局函数 全局函数可用于所有内建的 JavaScript 对象. (1) encodeURI():把字符串编码为 URI. <script ...

  6. js中的匿名函数和匿名自执行函数

    1.匿名函数的常见场景 js中的匿名函数是一种很常见的函数类型,比较常见的场景:   <input type="button" value="点击" id ...

  7. JS中关于把函数作为另一函数的参数的几点小总结

    //JS中关于把函数作为函数的参数来传递的问题的小总结//第一,最简单的形式无参函数,直接形式函数的函数名放到括号中,再在执行部分这个函数即可.//当然调用时要穿另一个真正的定义好的函数/*funct ...

  8. js中的Generators函数

    js中的Generators函数 generator一般操作 generator函数的作用就是函数体分段执行,yield表示分隔点 function *test() { console.log(1); ...

  9. JS中的回调函数实例浅析

    本文实例讲述了JS中的回调函数.分享给大家供大家参考,具体如下: 在说回调函数之前,不妨先看一段代码,相信有点js基础的同学都能明白他的含义: ? 1 2 3 document.getElementB ...

随机推荐

  1. openGL如何在改变窗口大小时,使自己的图形不被拉伸

    这里要注意两个概念:视口和视景体,当视口的纵横比和视景体的纵横比相同的时候,改变窗口大小,图像才不会变形: 视景体是指成像景物所在空间的集合.它是一个空间集合体. 单个的视景体,比如一个球体,若要完全 ...

  2. sed \s

    export m1=`free|cut -d ":" -f2|sed -e "s/^\s\s*//g"|head -2|tail -1|cut -d ' ' - ...

  3. nginx安装配置_runoob_阅读笔记_20190917

    Nginx 安装配置_runoob菜鸟教程 Nginx 安装配置 Nginx("engine x")是一款是由俄罗斯的程序设计师Igor Sysoev所开发高性能的 Web和 反向 ...

  4. springboot集成hibernate

    package com.jxd.Boot.hibernate.dao.impl; import java.util.List; import javax.persistence.EntityManag ...

  5. shelve模块 xml模块

    # import shelve# f=shelve.open('db.shl')# # f['stu1']={'name':'alex1','age':28}# # f['stu2']={'name' ...

  6. Spring---MongoDB

    1.MongoDB概述 1.1.NoSQL数据库 1.1.1.NoSQL的主要特点: 不使用SQL语言   作为查询条件: 数据存储  也不是固定的表.字段: 1.1.2.NoSQL数据库  主要有  ...

  7. macaca搭建

    对于新鲜的事务总是那么好奇,在自动化的过程中,有幸了解到macaca,记录下安装过程,具体介绍请移步官网:https://github.com/macacajs/ python版本参考:https:/ ...

  8. TCP TIME_WAIT和CLOSE_WAIT

    原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/11484451.html 使用如下指令查看当前Server的TCP状态 netstat -n | awk ...

  9. nyoj 119: 士兵杀敌(三) 【RMQ模板】

    题目链接 贴个板子.. #include<bits/stdc++.h> using namespace std; int n,q; ],d1[][],d2[][]; void RMQ_in ...

  10. 【leetcode】449. Serialize and Deserialize BST

    题目如下: Serialization is the process of converting a data structure or object into a sequence of bits ...