从日期列表中确定第二天

时间:2018-10-23 11:00:27

标签: javascript function

我有一个带有2个参数的函数。第一个参数是星期几(周一至周日为1-7,数字),第二个参数是可以具有不同数量的属性和值的对象:例如

    example1 = {day1: 5, day2: 2, day3: 1, day4: 7};
    example2 = {day1: 2, day2: 4, day3: 5};
    example3 = {day1: 2, day2: 6};

我想知道对象中的第二天(如果找到了当前日期,则第二天是当前日期),具体取决于一周中的当前日期。 例如:在星期六(currentDay = 6),example1的预期输出将为7,example2的输出将为2,example3的输出将为6。该对象也可以为空(然后返回为currentDay)。 。我的想法是遍历该对象并计算减去当前日期的日期,因此最低的数字将是第二天。如果所有数字都是负数,那么我们有一个新的星期。我对javascript很陌生。这是我的尝试,但我无法使其正常工作。

_determineNextDay = (currentDay, days) => {
    let negativeCheck = 0;
    let nextDay = currentDay;
    let countDays = 0;
    let calc = 0;
    for (let i in days) {
        countDays++;
        calc = days[i] - currentDay;
      if (calc < 0) {
        negativeCheck++;
      };
      if (calc >= 0 && calc < nextDay) {
        nextDay = calc + currentDay;
      };
    };
    calc = 0;
    if (negativeCheck == countDays && countDays > 0) {
      for (let i in days) {
        calc = days[i] - currentDay;
        if (calc < nextDay) {
          nextDay = calc;
        };
      };
      nextDay = nextDay + currentDay;
    };
    return nextDay;
  };

1 个答案:

答案 0 :(得分:0)

const find_closest_day = () => {
  const picked_days = Array
    .from( document.querySelectorAll( 'input:checked' ))
    .map( checkbox => checkbox.getAttribute( 'data-day' ))
  const current_day = new Date().getDay() || 7;
  const closest_day = picked_days.find( day => day >= current_day )
    || picked_days.sort().shift()
    || current_day;
  alert( closest_day );
};
document.querySelector( 'button' ).addEventListener( 'click', find_closest_day );
<ul>
  <li>
  <input type="checkbox" data-day="1">
  <span>Monday</span>
  </li>
  <li>
  <input type="checkbox" data-day="2">
  <span>Tuesday</span>
  </li>
  <li>
  <input type="checkbox" data-day="3">
  <span>Wednesday</span>
  </li>
  <li>
  <input type="checkbox" data-day="4">
  <span>Thursday</span>
  </li>
  <li>
  <input type="checkbox" data-day="5">
  <span>Friday</span>
  </li>
  <li>
  <input type="checkbox" data-day="6">
  <span>Saturday</span>
  </li>
  <li>
  <input type="checkbox" data-day="7">
  <span>Sunday</span>
  </li>
</ul>
<button>Closest</button>