提问者:小点点

如何避免在修改原始数组副本的同时更新原始数组? [副本]


在下面的代码中,我创建了一个名为updateCurrentYear()的新数组,并使用UpdateCurrentYear()函数修改其对象的date属性。

但是,每当我试图修改update[]中的birthd属性时,原始数组也会自动更新。 我怎样才能避免这种情况呢?

null

function birthdaySearch() {
  var birthdays = [
    { name: 'friend', birthday: new Date('03/25/1999') },
    { name: 'friend1', birthday: new Date('03/28/1999') },
    { name: 'friend2', birthday: new Date('09/25/1999') },
    { name: 'friend3', birthday: new Date('04/04/1999') },
    { name: 'friend4', birthday: new Date('07/05/1997') },
    { name: 'friend5', birthday: new Date('07/25/1998') }
  ];

  var nowDate = new Date();
  nowDate.setHours(0, 0, 0, 0);
  
  var nextMonth = nowDate.getMonth() + 1;
  var nextYear = nowDate.getFullYear() + 1;

  function updateToCurrentYear() {
    let update = [];
    birthdays.forEach(function(detail) {
      //.birthday.setFullYear(2020);
      update.push(detail);
    });
    
    update.forEach(function(update) {
      return update.birthday.setFullYear(nowDate.getFullYear());
    });
    
    console.log(update);
    return update;
  }

  return {
    updateToCurrentYear: updateToCurrentYear,
  }
}

birthdaySearchObj = birthdaySearch();
var current = birthdaySearchObj.updateToCurrentYear();

null


共2个答案

匿名用户

arr2=arr1将指向同一个数组。
使用arr2=arr1.slice()复制。
(若要比较数组,请使用:json.stringify(arr1)==json.stringify(arr2))。

匿名用户

为了避免复制值,您可以在此处使用扩展运算符映射:

null

function updateToCurrentYear() {
  /*let update = [];
        
   birthdays.forEach( function(detail) {
      //.birthday.setFullYear(2020);
        update.push(detail);
   } );*/
   const update = birthdays.map(b=>({...b}));
        
   update.forEach( function(update) {
      return update.birthday.setFullYear(nowDate.getFullYear() );
   });
   console.log(update);  
   
   return update;
}