最近遇到一个问题map方法不会修改原数组,会得到一个新数组并返回。但原数组真的不会修改吗?
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,"原数组");
一、在网上搜了一下,原来是上面的map方法不够“纯粹”,实际上还是直接修改了每个item的属性,如果不想影响原数组,应该这样写:
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,"原数组");
二、我们对对象数组中的item值,通过扩展运算符…深拷贝给obj,不在原数组中直接操作item的值,而是操作obj中的值,这样原数组就不会改变了。
1.当数组的值为基本类型的时候,map遍历数组,不会改变原数组。
2.当数组是一个对象数组时,map遍历数组,原数组发生改变