javascript - 如何每次使用 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 日)。
解决方案
您可能正在这里寻找函数闭包。使用它,您将能够存储您最初调用该函数的日期,然后每次再次调用它时,它将在最后打印的第 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());
希望这可以帮助 !
推荐阅读
- elasticsearch - 弹性:错误 400(错误请求):未能执行脚本 [type=illegal_argument_exception]
- elasticsearch - 从 Elasticsearch 中同步删除文档
- python - 如何在基于 Alpine 图像的 dockerized 应用程序中启用 WebSocket 连接(WebSocketAddressException:[Errno -3])?
- java - 无法自动接线。找不到“int”类型的 bean
- java - 每像素字节数,每行字节数 - 如何在 tess-two 的 tessbaseapi.cpp 中使用函数 nativeSetImageBytes?
- java - Don't know the simplest way to display my matrix in a column, keeps displaying in one row
- c++ - 在 stl 排序算法中未调用自定义交换函数
- elasticsearch - 使用 ElasticSeach 搜索字符串的一部分
- orientdb - 尝试连接到本地 orientdb 数据库时,“配置文件格式无效”
- mongodb - MongoDB 对匹配所有值的电子邮件地址进行全文搜索,并可能修复花费太多时间