所以,我有以下功能

function toDays(startDateString, endDateString) {

  const startDate = moment(startDateString, 'dddd MMM DD YYYY');
  const endDate = moment(endDateString, 'dddd MMM DD YYYY');

  const dates = [];

  while(startDate.isSameOrBefore(endDate, 'day')) {
    const currentDay = startDate.format('dddd');
    dates[currentDay].push({start:'9:00', end:'18:00'});
    startDate.add(1, 'days');
  }

  return dates;
}

const result = toDays('Monday Dec 24 2018', 'Friday Dec 28 2018');
console.log(result);


当我使用dates[currentDay].push({start:'9:00', end:'18:00'});时,它返回一个错误,我试图实现的是在currentDay上推送这些键,就像在数组上推送对象一样。错误是Uncaught TypeError: Cannot read property 'push' of undefined
但是,如果我使用
dates[currentDay] = {start:'9:00', end:'18:00'};它工作正常,但我不确定这是否正确。有什么想法吗?

最佳答案

dates数组没有索引为currentDay的项目。
尝试以下操作以亲自查看:

const currentDay = startDate.format('dddd');
var obj = dates[currentDay];
console.log(obj);
obj.push({start:'9:00', end:'18:00'});
startDate.add(1, 'days');


将此代码放在while()语句中。它将在控制台undefined上输出。

要解决此问题,请测试currentDay是否在dates中或适当地填充dates,如下所示:

if (typeof dates[currentDay] === "undefined") // test
{
  // does not exist, yet: initialize
  dates[currentDay] = [];
}

// ...
dates[currentDay].push(...);

关于javascript - 将obj推到arr时,函数输出异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53944191/

10-12 06:43