javascript函数返回星期几x天数后

时间:2019-01-03 02:41:09

标签: javascript arrays dictionary

我要写的是一个简单的函数,它需要一天(D)的时间,即X天数,然后在X天后返回该天。

日子可以用(“星期一”,“星期二”,“星期三”,“星期四”,“星期五”,“星期六”,“星期日”)表示。

X可以是任何int 0或更高。

例如,D ='Wed',X ='2',返回'Fri',D ='Sat',X ='5',返回'Wed'。

如何在JS中执行此操作?任何提示和建议都表示赞赏。

1 个答案:

答案 0 :(得分:1)

如果我正确理解了您的问题,那么也许您可以执行以下操作:

  1. 找到输入“ d”相对于星期几的索引
  2. 应用“ x”以抵消找到的索引
  3. 按总天数(7)应用模运算符,以使偏移量指数围绕有效日期范围旋转
  4. 通过该计算索引返回结果日

这是一个代码段-希望对您有所帮助!

function getWeekDayFromOffset(d, x) {

  // Array of week days
  const days = ['Mon', 'Tue', 'Wed', 'Thu','Fri','Sat','Sun'];
  
  // Find index of input day "d"
  const dIndex = days.indexOf(d);
  
  // Take add "x" offset to index of "d", and apply modulo % to
  // revolve back through array
  const xIndex = (dIndex + x) % days.length;
  
  // Return the day for offset "xIndex"
  return days[xIndex];
}

console.log('returns Fri:', getWeekDayFromOffset('Wed', 2));
console.log('returns Thu:', getWeekDayFromOffset('Sat', 5));