在下面的代码中,我创建了一个名为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
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;
}