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

应该一次循环就能搞定吧


  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);


繁花不似锦
浏览 739回答 2
2回答

四季花海

const week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']const weekdata = week.map((day, idx) => newData.reduce((item, v) => item + parseFloat(v[day]), 0)后面那块逻辑是按照你代码搬过来了,出问题不怪我 :)

海绵宝宝撒

安利一下柯里化:const getTotal = function (list) {    return function (day) {        return list.reduce((result, item) => (            result + parseFloat(item[day])        ), 0);    };}const getWeekdayTotal = getTotal(newData);// single daylet mondayTotal = getWeekdayTotal("Monday");let tuesdayTotal = getWeekdayTotal("Tuesday");// multiple dayslet days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];let daysTotal = days.map(getWeekdayTotal);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript