首页 > 解决方案 > 如何每次使用 javascript 和 jquery 获得下一个第 6 个日期

问题描述

function sixthDate() {
  var curr = new Date(); // get current date
  curr.setDate(curr.getDate() + 6);
  return curr;
}
console.log(sixthDate());

它每次都向我展示相同的第 6 次约会!但我每次打电话时都想要下一个第 6 天(比如:2020 年 6 月 18 日 + 6 = 2020 年 6 月 24 日,6 月 24 日 + 6 = 6 月 30 日)。

标签: javascriptjquerydatetime

解决方案


您可能正在这里寻找函数闭包。使用它,您将能够存储您最初调用该函数的日期,然后每次再次调用它时,它将在最后打印的第 6 个日期之后打印第 6 个日期。

function sixthDate() {
  var curr = new Date(); // get current date
  curr.setDate(curr.getDate() + 6);
  return curr;
}

console.log("Normal function - ");
//prints same 6th dates everytime
console.log(sixthDate().toDateString());
console.log(sixthDate().toDateString());

const getNewSixthDate = function() {
  var curr = new Date;
  return function() {
    curr.setDate(curr.getDate() + 6);
    // returning a copy and not the reference
    // so that curr doesn't get modified outside function
    return new Date(curr);
  }
}();


console.log("\nUsing Function Closures -");
// prints the 6th date, stores it
// and then prints the 6th date after that next time
// This process will repeat everytime
console.log(getNewSixthDate().toDateString());
console.log(getNewSixthDate().toDateString());
console.log(getNewSixthDate().toDateString());

希望这可以帮助 !


推荐阅读