为了账号安全,请及时绑定邮箱和手机立即绑定

帮忙优化一下代码,总觉得自己写的好麻烦,哪里不太对?

帮忙优化一下代码,总觉得自己写的好麻烦,哪里不太对?

繁花不似锦 2019-02-13 16:15:25
应该一次循环就能搞定吧  let MondayTotal = 0;  MondayTotal = newData.reduce((item, v) => {    return item + parseFloat(v.Monday);  }, MondayTotal);  let TuesdayTotal = 0;  TuesdayTotal = newData.reduce((item, v) => {    return item + parseFloat(v.Tuesday);  }, TuesdayTotal);  let WednesdayTotal = 0;  WednesdayTotal = newData.reduce((item, v) => {    return item + parseFloat(v.Wednesday);  }, WednesdayTotal);  let ThursdayTotal = 0;  ThursdayTotal = newData.reduce((item, v) => {    return item + parseFloat(v.Thursday);  }, ThursdayTotal);  let FridayTotal = 0;  FridayTotal = newData.reduce((item, v) => {    return item + parseFloat(v.Friday);  }, FridayTotal);  let SaturdayTotal = 0;  SaturdayTotal = newData.reduce((item, v) => {    return item + parseFloat(v.Saturday);  }, SaturdayTotal);  let SundayTotal = 0;  SundayTotal = newData.reduce((item, v) => {    return item + parseFloat(v.Sunday);  }, SundayTotal);
查看完整描述

2 回答

?
四季花海

TA贡献1811条经验 获得超5个赞

const week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']


const weekdata = week.map((day, idx) => newData.reduce((item, v) => item + parseFloat(v[day]), 0)

后面那块逻辑是按照你代码搬过来了,出问题不怪我 :)

查看完整回答
反对 回复 2019-02-25
?
海绵宝宝撒

TA贡献1809条经验 获得超8个赞

安利一下柯里化:


const getTotal = function (list) {

    return function (day) {

        return list.reduce((result, item) => (

            result + parseFloat(item[day])

        ), 0);

    };

}


const getWeekdayTotal = getTotal(newData);


// single day

let mondayTotal = getWeekdayTotal("Monday");

let tuesdayTotal = getWeekdayTotal("Tuesday");


// multiple days

let days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];

let daysTotal = days.map(getWeekdayTotal);


查看完整回答
反对 回复 2019-02-25
  • 2 回答
  • 0 关注
  • 738 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信