简体   繁体   English

javascript - 如何不通过引用分配

[英]javascript - how to NOT assign by reference

Okay consider this bit of code: 好的,考虑一下这段代码:

var d1 = new Date();
var d2 = d1;

d2.setDate(d2.getDate()+1);
alert(d1 + "\n" + d2);

Even though I call setDate() on d2 , d1 is also being incremented. 即使我在d2上调用setDate()d1也会递增。 I understand this to be because d1 is assigned to d2 by reference. 我理解这是因为d1通过引用分配给d2 My question is...how do I NOT do this, so that .setDate() only gets applied to d2 ? 我的问题是......我怎么不这样做,所以.setDate()只能应用到d2

In JavaScript, all objects are assigned to variables 'by reference' . 在JavaScript中, 所有对象都通过引用分配给变量 You need to create a copy of the object; 您需要创建对象的副本; Date makes it easy: Date变得简单:

var d2 = new Date(d1);

This will create a new date object copying d1 's value. 这将创建一个复制d1值的新日期对象。

You need 你需要

var d2 = new Date(d1.getTime());

See How to clone a Date object in JavaScript for more details. 有关更多详细信息,请参见如何在JavaScript中克隆Date对象

Think this should work: 认为这应该工作:

var d1 = new Date();
var d2 = new Date();
d2.setDate(d1.getDate());

d2.setDate(d2.getDate()+1);
alert(d1 + "\n" + d2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM