代码之家  ›  专栏  ›  技术社区  ›  coinhndp

克隆js对象

  •  1
  • coinhndp  · 技术社区  · 8 年前

    我的momentjs对象处于状态

      state = {
         startDate: getNow() //this funtion return a momemtJS object
        }
    

    在一个函数中,我需要得到startDate前一年的日期

    const dateBeforeOneYear=本州开始日期.减去(1,'年');

    但是如果我这样做,我会错误地修改状态

    所以我试着复制这个状态

    const copyStartDate = {...this.state.startDate}
    
    const copyStartDate = this.state.startDate.subtract(1, 'years');
    

    但是现在我得到了一个错误,substract不是一个函数,我猜是因为copyStartDate不再是momentTjs了

    2 回复  |  直到 8 年前
        1
  •  19
  •   Tom Fenech    8 年前

    There's a method 要克隆力矩对象,请执行以下操作:

    const yearBefore = this.state.startDate.clone().subtract(1, 'years');
    

    .valueOf() 在某个日期或某个时刻,其中任何一个都返回自UNIX纪元以来的毫秒数。

        2
  •  8
  •   bathpp    8 年前

    瞬间.js有自己的用于克隆矩对象的api。

    var copy = momentObj.clone();

    我同意存储日期序列化表示,而不是存储对象。

        3
  •  1
  •   JayCodist    6 年前

    也可以复制 moment 对象通过其构造函数。就像这样

    const firstMoment = moment("2020-08-18");
    const clone = moment(firstMoment);
    
    推荐文章