【问题标题】:Date parameter in function [duplicate]函数中的日期参数
【发布时间】:2018-10-22 09:12:24
【问题描述】:

我想将日期传递给 javascript 函数以进行一些操作。我在这里面临的问题是:该函数正在更改实际的日期参数,尽管它适用于本地参数。这是我提到我的问题的一个例子

var myDate = new Date();
console.log(myDate);//Result is Mon Oct 22 2018 09:40:01
function manipulate(d){
    d.setDate(d.getDate()+1);
    console.log(d);//Result is Oct 23 2018 09:40:01
    return d;
}
var result = manipulate(myDate);
console.log(result);//Result is Oct 23 2018 09:40:01 as expected.
console.log(myDate);//Result is Oct 23 2018 09:40:01. I want this to be my initial value. That is Mon Oct 22 2018 09:40:01

如果日期用作参数,我猜它 JS 使用按引用传递。 如何解决上述问题?

问候,

SAP 学习者

【问题讨论】:

  • 尝试在函数中获取日期的副本,如下所示: var dLocalCopyFrom = new Date(d.getTime()); dLocalCopyFrom.setDate(dLocalCopyFrom.getDate()+1);这不会改变实际日期
  • 使用 Date 对象的 getTime() 函数获取克隆。 stackoverflow.com/questions/1090815/…

标签: javascript date


【解决方案1】:

你必须先复制它

function manipulate(d){
    var s = new Date(d)
    s.setDate(s.getDate()+1);
    console.log(s);//Result is Oct 23 2018 09:40:01
    return s;
}

【讨论】:

  • new Date(d) 就足够了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-04
  • 1970-01-01
  • 2011-12-28
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
  • 1970-01-01
相关资源
最近更新 更多