将obj推到arr时的函数输出很奇怪

时间:2018-12-27 11:17:50

标签: javascript arrays

所以,我有以下功能

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'}; 可以正常工作,但是我不确定这是否正确。有什么想法吗?

3 个答案:

答案 0 :(得分:2)

首先检查日期[currentDay]是否存在。如果没有,则日期[currentDay] = []在推送之前。

dates [currentDay] = {开始:'9:00',结束:'18:00'}正在工作,因为它是直接在最初未定义的位置上分配对象。

答案 1 :(得分:1)

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

答案 2 :(得分:0)

问题是您试图将对象推到尚不存在的某个位置。您提出的方法:

dates[currentDay] = {start: '9:00', end: '18:00'}

这是最核心的方法,尽管您实际上不应该修改常量变量,否则您的代码会中断。为防止此问题,请使用:

var dates = [];

代替:

const dates = [];