循环在javascript循环中

时间:2016-10-16 02:59:57

标签: javascript coffeescript

我试图在循环中运行循环以获得一些有效的日期,但似乎没有正常工作。我的样本数据就像

这些是有效的日子 [ 'Monday', 'Thursday', 'Friday', 'Sunday' ]

这些是有效日期

[ Sun Oct 09 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
  Mon Oct 10 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
  Tue Oct 11 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
  Wed Oct 12 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
  Thu Oct 13 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
  Fri Oct 14 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
  Sat Oct 15 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
  Sun Oct 16 2016 05:00:00 GMT+0500 (Pakistan Standard Time) ]

我想要做的是:只找到那些等于vaid天的日期

我在做什么:

_valid_dates = (dates, days) ->
  validDates = dates
  dates.forEach (date) ->
    days.forEach (day) ->
      if moment_strf(date).strftime("%A") != day
        validDates.remove date
      else
        console.log "Am valid day", moment_strf(date).strftime("%A")

  validDates

但结果并没有像我期待的那样到来。根据数据,剩余日期应为

[ Sun Oct 09 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
  Mon Oct 10 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
  Thu Oct 13 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
  Fri Oct 14 2016 05:00:00 GMT+0500 (Pakistan Standard Time),
  Sun Oct 16 2016 05:00:00 GMT+0500 (Pakistan Standard Time) ]

任何帮助将不胜感激!感谢

1 个答案:

答案 0 :(得分:-1)

您只需使用javascript即可完成:

不是在日期数组中使用全名,而是可以使用0-6天,然后

    //sunday=0,monday=1 ....saturday=6
     var days=[1,4,5,0];
     var result_arr=[]; // required array for result
     for(date in dates)
     {
        if(days.indexOf(new Date(date).getDay())!=-1)
         {
             result_arr.push(date);
         }
      }