I encountered a problem recently. The map method will not modify the original array, but will get a new array and return it. But is the original array really not modified?
let tableDate = [
{
enableAssigned: false,
enableNotified: false,
finishedAt: 1679414400000,
startedAt: 1678809600000,
username: "",
},
{
enableAssigned: false,
enableNotified: false,
finishedAt: 1679414400000,
startedAt: 1678809600000,
username: "",
},
];
let arr = tableDate.map((item)=>{
item.finishedAt = item.finishedAt/1000
item.startedAt = item.startedAt/1000
return item
}
)
console.log(arr,"新数组");
console.log(tableDate,"原数组");
1. After searching on the Internet, it turns out that the above map method is not "pure" enough. In fact, it directly modifies the attributes of each item. If you don't want to affect the original array, you should write it like this:
let tableDate = [
{
enableAssigned: false,
enableNotified: false,
finishedAt: 1679414400000,
startedAt: 1678809600000,
username: "",
},
{
enableAssigned: false,
enableNotified: false,
finishedAt: 1679414400000,
startedAt: 1678809600000,
username: "",
},
];
let arr = tableDate.map((item)=>{
return {...item,startedAt:item.startedAt/1000,finishedAt:item.finishedAt/1000}}
)
// let arr = tableDate.map((item)=>({...item,startedAt:item.startedAt/1000,finishedAt:item.finishedAt/1000}))
console.log(arr,"新数组");
console.log(tableDate,"原数组");
2. We deep copy the item value in the object array to obj through the spread operator... instead of directly operating the item value in the original array, but operating the value in obj, so that the original array will not change.
1. When the value of the array is a basic type, map traverses the array without changing the original array.
2. When the array is an object array, map traverses the array and the original array changes.