为什么map会改变对象的数组? [英] Why does map mutate array of objects?

查看:37
本文介绍了为什么map会改变对象的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能是一个愚蠢的问题,但是为什么map会改变对象的数组.

Might be a stupid question, but why does map mutate array of objects.

var obj = {
  items: [{
    value: 1,
    selected: true
  }, {
    value: 2,
    selected: false
  }]
};

var items = obj.items.map(i => {
  if (i.value === 2) i.selected = true;
  return i;
});

console.log(obj);

推荐答案

映射数组时,它不是在创建对象的副本.它只是遍历数组.

When you map an array, it's not creating a copy of the object. It's just iterating over the array.

如果您不想变异对象,则必须创建该对象的副本:

If you don't want to mutate the object, you have to create a copy of the object:

var items = obj.items.map(item => {
    let i = JSON.parse(JSON.stringify(item))
    if (i.value === 2) i.selected = true;
    return i;
});

这篇关于为什么map会改变对象的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆