Javascript 把从现在到一天结束的所有时间分开

Javascript 把从现在到一天结束的所有时间分开,javascript,momentjs,Javascript,Momentjs,因此,我想将一天中剩余的所有时间分割成一个数组,例如,如果实际时间是下午3:00,我希望有一个数组,例如[4pm、5pm、6pm、7pm、…、11pm] 我使用moment.js尝试了类似的东西,但运气不好 var now = moment().startOf('hour'); $('div').append(now + "<br>"); var count = 0; while (now < moment().endOf('day')) { count += 30;

因此,我想将一天中剩余的所有时间分割成一个数组,例如,如果实际时间是下午3:00,我希望有一个数组,例如[4pm、5pm、6pm、7pm、…、11pm]

我使用moment.js尝试了类似的东西,但运气不好

var now = moment().startOf('hour');
$('div').append(now + "<br>");
var count = 0;
while (now < moment().endOf('day')) {
  count += 30;
  now = now.add(count, 'minutes').format("hh:mm a");
  $('div').append(now + "<br>");
}
var now=moment().startOf('hour');
$('div')。追加(现在+“
”); var计数=0; while(现在”); }
如何实现我的目标?

您可以创建一个包含所有小时的列表,然后删除
n
th第一个条目,其中
n
是当前的24小时时间,如下所示:

var now = moment().startOf('hour');
var all_hours=['12pm', '1am', '2am', '3am', '4am', '5am', '6am', '7am', '8am', '9am', '10am', '11am', '12am', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm', '8pm', '9pm', '10pm', '11pm'];
var remaining_hours=all_hours.slice(parseInt(now.format("H")), all_hours.length-1);
话虽如此,我想你之所以要做一个循环是因为这是一个循环,而不是你在生产中真正要做的。因此,基于您的示例,以下内容应该可以工作

// Get current hour
var now = moment().startOf('hour');
// Get the 24 hour time
var this_hr_int24=parseInt(now.format("H"));
// The list to contain the remaining hours
var remaining_hours=[];
// Initialize loop variables
next_hr_int24=this_hr_int24;
next_hr=now;
// While the number in next_hr_int24 is less then 24
while (next_hr_int24 < parseInt(moment().endOf('day').format("H"))) {
  // Increase by 60
    var count = 60;
  // Next hour of day
  next_hr = next_hr.add(count, 'minutes')
  // Get the 24 hr time for the next hour
  next_hr_int24 = next_hr.format("H")
  // Get the am/pm value for the list
  next_hr_apm = next_hr.format("h a")

  remaining_hours.push(next_hr_apm);
}
//获取当前小时数
var now=moment().startOf('hour');
//得到24小时的时间
var this_hr_int24=parseInt(now.format(“H”);
//包含剩余小时数的列表
var剩余时间=[];
//初始化循环变量
next_hr_int24=此_hr_int24;
下一步=现在;
//而next_hr_int24中的数字小于24
while(next_hr_int24
那么第一个示例对于生产来说是更好的实践?如果我把每小时的时间都记在“下午2点”上,再多记半小时“下午2点30分”,会不会有同样的效果。谢谢你的帮助help@fmonper1经验法则是,除非必须,否则不想对循环使用
。这里的另一件事是,在第一个例子中,函数调用更少,内置更多,这(通常)使代码更易于阅读和执行。你的问题似乎暗示你想要,但我不确定你在做什么,或者为什么,加上30分钟?如果你认为它是令人满意的,请考虑投票赞成答案和/或接受答案!