gpt4 book ai didi

复制数组上的 Javascript .map()

转载 作者:行者123 更新时间:2023-11-30 14:13:30 25 4
gpt4 key购买 nike

我注意到在不将其分配给变量的情况下调用 .map() 会使它返回整个数组,而不仅仅是更改的属性:

const employees = [{
name: "John Doe",
age: 41,
occupation: "NYPD",
killCount: 32,
},
{
name: "Sarah Smith",
age: 26,
occupation: "LAPD",
killCount: 12,
},
{
name: "Robert Downey Jr.",
age: 48,
occupation: "Iron Man",
killCount: 653,
},

]

const workers = employees.concat();

workers.map(employee =>
employee.occupation == "Iron Man" ? employee.occupation = "Philantropist" : employee.occupation
);

console.log(employees);

但考虑到 .concat() 创建了原始数组的副本并将其分配给 worker,为什么 employee 也会发生变异?

最佳答案

发生这种情况是因为数组中的对象仍被相同的指针引用。 (您的数组仍然引用内存中的相同对象)。此外,Array.prototype.map() 总是返回一个数组,它的结果应该分配给一个变量,因为它不进行就地 映射。当您在 map 方法中更改对象的属性时,您应该考虑改用 .forEach() 来修改复制的 employees 数组中对象的属性。要复制您的员工数组,您可以使用以下命令:

const workers = JSON.parse(JSON.stringify(employees));

请看下面的例子:

const employees = [
{
name: "John Doe",
age: 41,
occupation: "NYPD",
killCount: 32,
},
{
name: "Sarah Smith",
age: 26,
occupation: "LAPD",
killCount: 12,
},
{
name: "Robert Downey Jr.",
age: 48,
occupation: "Iron Man",
killCount: 653,
},

]


const workers = JSON.parse(JSON.stringify(employees));
workers.forEach(emp => {
if(emp.occupation == "Iron Man") emp.occupation = "Philantropist";
});

console.log("--Employees--")
console.log(employees);
console.log("\n--Workers--");
console.log(workers);

  • 注意:如果您的数据中有任何方法,您需要使用其他方法进行深拷贝

关于复制数组上的 Javascript .map(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53966191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com