美文网首页
递归遍历

递归遍历

作者: 家有饿犬和聋猫 | 来源:发表于2019-08-20 17:04 被阅读0次

    数据加和,使用递归遍历,对任何的子嵌套都有用

    let company = { 
      sales: [{name: 'John', salary: 1000}, {name: 'Alice', salary: 600 }],
      development: {
                    sites: [{name: 'Peter', salary: 2000}, {name: 'Alex', salary: 1800 }],
                    internals: [{name: 'Jack', salary: 1300   }]
      }
    };
    //用来完成工作的函数
    function sumSalaries(department) {
        if (Array.isArray(department)) {
                   //prev  加和后的值,    current当前值
            return department.reduce((prev, current) => prev + current.salary, 0);  //求数组的和
        } else {
            let sum = 0;
            for (let subdep of Object.values(department)) {
                     //Object.values   取对象的值
                sum += sumSalaries(subdep);     //递归调用子对象,对结果求和
            }
            return sum;
        }
    }
    alert(sumSalaries(company));    //6700
    
    

    相关文章

      网友评论

          本文标题:递归遍历

          本文链接:https://www.haomeiwen.com/subject/roipsctx.html