dateJS 正在覆盖变量
我刚刚开始使用 dateJS,它似乎是一个很棒的库,但我显然错过了一些东西(可能是一个愚蠢的错误),但在我的函数中我需要 3 个日期:clickedDate、weekStart 和 weekStart。周末。但使用 dateJS 我似乎覆盖了每个变量。有人可以指出我的错误吗?
var clickDate = myDate;
console.log(clickDate);
var weekStart = Date.parse(clickDate).last().monday();
console.log(clickDate);
var weekEnd = Date.parse(clickDate).next().sunday();
console.log(weekEnd);
console.log('break');
console.log(clickDate);
console.log(weekStart);
console.log(weekEnd);
控制台显示如下
Date {Wed Nov 30 2011 00:00:00 GMT-0700 (US Mountain Standard Time)}
Date {Mon Nov 28 2011 00:00:00 GMT-0700 (US Mountain Standard Time)}
Date {Sun Dec 04 2011 00:00:00 GMT-0700 (US Mountain Standard Time)}
break
Date {Sun Dec 04 2011 00:00:00 GMT-0700 (US Mountain Standard Time)}
Date {Sun Dec 04 2011 00:00:00 GMT-0700 (US Mountain Standard Time)}
Date {Sun Dec 04 2011 00:00:00 GMT-0700 (US Mountain Standard Time)}
I am just starting with dateJS and it seems like a great lib but I am obviously missing something (probably a stupid mistake) but in my function I need 3 dates: clickedDate, weekStart & weekEnd. But using dateJS I seem to be overwritting each variable. Can someone please point out my mistake?
var clickDate = myDate;
console.log(clickDate);
var weekStart = Date.parse(clickDate).last().monday();
console.log(clickDate);
var weekEnd = Date.parse(clickDate).next().sunday();
console.log(weekEnd);
console.log('break');
console.log(clickDate);
console.log(weekStart);
console.log(weekEnd);
The console shows the following
Date {Wed Nov 30 2011 00:00:00 GMT-0700 (US Mountain Standard Time)}
Date {Mon Nov 28 2011 00:00:00 GMT-0700 (US Mountain Standard Time)}
Date {Sun Dec 04 2011 00:00:00 GMT-0700 (US Mountain Standard Time)}
break
Date {Sun Dec 04 2011 00:00:00 GMT-0700 (US Mountain Standard Time)}
Date {Sun Dec 04 2011 00:00:00 GMT-0700 (US Mountain Standard Time)}
Date {Sun Dec 04 2011 00:00:00 GMT-0700 (US Mountain Standard Time)}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不是 Datejs 的问题,而是 JavaScript Date 对象的一个特性(?)。在 JavaScript 中,Date 对象是可变的,将
Date
对象值设置为新变量会创建对原始对象的引用,而不是新对象。这可以使用普通的旧 JavaScript(无 Datejs)来演示:
Exmaple
如果使用 Datejs,解决此问题的方法是“克隆”Date 对象。以下示例演示了在“b”和“c”Date 对象上使用
.clone()
函数。示例
运行上面的代码,您应该会看到“b”和“c”的最终结果仍然反映其原始值,即使“a”已更改。
希望这有帮助。
This isn't an issue with Datejs, but a feature(?) of JavaScript Date objects. In JavaScript, the Date object is mutable, and setting a
Date
object value to a new variable creates a reference to the original, not a new object.This can be demonstrated using plain old JavaScript (no Datejs):
Exmaple
The way to work around this if using Datejs is by "cloning" the Date objects. The following sample demonstrates the use of the
.clone()
function on the 'b' and 'c' Date objects.Example
Running the above, you should see the final results of 'b' and 'c' still reflect their original values even though 'a' has changed.
Hope this helps.