Как я могу каждый раз получать следующую шестую дату, используя javascript и jquery - PullRequest
1 голос
/ 17 июня 2020

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

Он просто показывает мне каждый раз одну и ту же 6-ю дату! Но мне нужно следующее 6-е свидание каждый раз, когда я звоню (например: 18 июня 2020 г. + 6 = 24 июня 2020 г., 24 июня + 6 = 30 июня).

1 Ответ

3 голосов
/ 17 июня 2020

Вероятно, вы ищете здесь закрытие функции . Используя это, вы сможете сохранить дату, когда вы изначально вызвали функцию, а затем каждый раз, когда вы вызываете ее снова, она будет печатать 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());

Надеюсь, это поможет!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...