1

我刚从 dateJS 开始,它似乎是一个很棒的库,但我显然遗漏了一些东西(可能是一个愚蠢的错误),但在我的函数中,我需要 3 个日期:clickedDate、weekStart 和 weekEnd。但是使用 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)}
4

1 回答 1

3

这不是 Datejs 的问题,而是 JavaScript Date 对象的一个​​特性(?)。在 JavaScript 中,Date 对象是可变的,将Date对象值设置为新变量会创建对原始对象的引用,而不是新对象。

这可以使用普通的旧 JavaScript(没有 Datejs)来演示:

示例

var a = new Date(2011, 0, 1);
var b = a;
var c = b;

console.log('a', a); // 1-Jan-2011
console.log('b', b); // 1-Jan-2011
console.log('c', c); // 1-Jan-2011

// setting only 'a' will cause 'b' and 'c' to update as well.
a.setDate(10);

console.log('a', a); // 10-Jan-2011
console.log('b', b); // 10-Jan-2011
console.log('c', c); // 10-Jan-2011

如果使用 Datejs,解决此问题的方法是“克隆” Date 对象。下面的示例演示了.clone()在“b”和“c”日期对象上使用该函数。

例子

var a = new Date(2011, 0, 1);
var b = a.clone(); // clone creates a new 'copy' of 'a'.
var c = b.clone();

console.log('a', a); // 1-Jan-2011
console.log('b', b); // 1-Jan-2011
console.log('c', c); // 1-Jan-2011

a.setDate(10);

console.log('a', a); // 10-Jan-2011
console.log('b', b); // 1-Jan-2011
console.log('c', c); // 1-Jan-2011

运行上面的代码,你应该看到 'b' 和 'c' 的最终结果仍然反映了它们的原始值,即使 'a' 已经改变了。

希望这可以帮助。

于 2011-11-21T23:21:38.690 回答