香草JS for循环问题

时间:2020-04-25 08:10:31

标签: javascript for-loop scope return

在rosteringArray()中遍历for循环,array应该是这样的。

array [0] = startDate(以毫秒为单位)

array [1] = startDate(以毫秒为单位)+ 86400000

...

array [array.length-1] = endDate(以毫秒为单位)

但事实并非如此。

如何开发此代码?

var rosteringArray = function(yy1, mm1, dd1, yy2, mm2, dd2){
  var date = new Date(yy1,mm1,dd1);
  var sDate = new Date(date);

  var timeStart = date.getTime() + 86400000*9; //

  var date = new Date(yy2,mm2,dd2);
  var sDate = new Date(date);

  var timeEnd = date.getTime() + 86400000*9;

  var end = timeStart;
  var start = timeEnd;
  
  var countDateBetween = (end - start)/86400000 +1;
  var array = new Array;
  for (var g = 0; g < countDateBetween; g++){
    for (var h =setStart; h < setEnd; h=h+86400000){
    array[g] = h;
    return array;
    }
  }
}

console.log(rosteringArray(2020,0,1,2020,0,03));

1 个答案:

答案 0 :(得分:1)

您混合了属性值:

var end = timeStart; var start = timeEnd;

并且您不需要第二个循环,该循环将始终为数组中的所有属性设置前一天的值。

看看工作片段:

var rosteringArray = function(yy1, mm1, dd1, yy2, mm2, dd2){
  var date = new Date(yy1,mm1,dd1);
  var sDate = new Date(date);

  var timeStart = date.getTime() + 86400000*9; //

  var date = new Date(yy2,mm2,dd2);
  var sDate = new Date(date);

  var timeEnd = date.getTime() + 86400000*9;

  var end = timeEnd;
  var start = timeStart;
  console.log(start);
  console.log(end);
  
  var countDateBetween = (end - start)/86400000 +1;
  console.log(countDateBetween);
  var array = new Array;
  var h =start;
  for (var g = 0; g < countDateBetween; g++){
    
    array[g] = h;
    h=h+86400000;
    }
return array;
}

console.log(rosteringArray(2020,0,1,2020,0,03));