【问题标题】:Angular - Pushing elements into an array in a loop updates all the preexisting values of the array with the new valueAngular - 在循环中将元素推送到数组中会使用新值更新数组的所有预先存在的值
【发布时间】:2019-05-22 13:26:57
【问题描述】:

我将一周中的日期推送到一个数组中。

如果您可以参考代码,请在 //good value 行中 数组有正确的值

但是每次 dates.setDate(dates.getDate() + 1 ); 执行

所有数组值都会自动更新为新值。 它不是仅仅推入数组中的新元素,而是推入数组中的新元素,并用新元素替换数组中的所有元素

  this.mondayDate = this.getMonday(this.viewDate);
  let dates = this.mondayDate;
  this.datesOfTheWeek = [];
  this.datesOfTheWeek.push(this.mondayDate);
  console.log(this.datesOfTheWeek);
  for(let i in [1,2,3,4,5,6]){
    console.log(this.datesOfTheWeek); // good value in the array
    dates.setDate(dates.getDate() + 1 );
    console.log(this.datesOfTheWeek); // bad value in the array

    this.datesOfTheWeek.push(dates);
    console.log(this.datesOfTheWeek);
  }

  console.log(this.datesOfTheWeek);

第一次迭代://仅包含星期一日期-//错误值的输出

Array(1) [2019 年 5 月 21 日星期二 15:17:46 GMT+0200(heure d'été d'E...]

第二次迭代://从//错误值推送星期二日期-输出

Array(2) [2019 年 5 月 22 日星期三 15:17:46 GMT+0200(时间点……,2019 年 5 月 22 日星期三 15:17:46 GMT+0200(时间点) …]

最后的数组值为

Array(6) [2019 年 5 月 26 日星期日 15:17:46 GMT+0200(时间点……,2019 年 5 月 26 日星期日 15:17:46 GMT+0200(时间点) …,2019 年 5 月 26 日星期日 15:17:46 GMT+0200(时间点)…,2019 年 5 月 26 日星期日 15:17:46 GMT+0200(时间点…,2019 年 5 月 26 日星期日15:17:46 GMT+0200 (heure d'été d'E…, Sun May 26 2019 15:17:46 GMT+0200 (heure d'été d'E…]

但它应该包含从 5 月 20 日到 5 月 26 日的日期

【问题讨论】:

    标签: arrays angular date


    【解决方案1】:

    那是因为dates 看起来是一个 Date 对象,而不是原始对象(因此,如果您对其进行变异,对它的所有引用都将指向变异值)。您需要创建一个副本:而不是

        dates.setDate(dates.getDate() + 1 );
        console.log(this.datesOfTheWeek); // bad value in the array
    
        this.datesOfTheWeek.push(dates);
    

    做类似的事情

        let newDate = new Date(dates);
        newDate.setDate(dates.getDate() + 1 );
        console.log(this.datesOfTheWeek);
    
        this.datesOfTheWeek.push(newDate);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-02
      • 2017-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-06
      • 1970-01-01
      相关资源
      最近更新 更多