为什么数组上的js映射会修改原始数组? [英] why a js map on an array modify the original array?

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

问题描述

我对map()的行为感到很困惑。

I'm quite confuse by the behaviour of map().

我有一个像这样的对象数组:

I have an array of objects like this :

const products = [{
    ...,
    'productType' = 'premium',
    ...
}, ...]

我将这个数组传递给一个应该返回相同的函数数组,但所有产品免费:

and i'm passing this array to a function that should return the same array but with all product made free :

[{
    ...,
    'productType' = 'free',
    ...
}, ...]

该函数是:

const freeProduct = function(products){
    return products.map(x => x.productType = "free")
}

返回以下数组:

["free", "free", ...]

所以我把我的函数重写为:

So i rewrote my function to be :

const freeProduct = function(products){
    return products.map(x => {x.productType = "free"; return x})
}

按预期返回数组。

但是!那是我放松心情的时刻,在这两种情况下我的原始产品阵列都被修改了。

BUT ! And that's the moment where i loose my mind, in both cases my original products array is modified.

map()周围的文档说它不应该( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map )。

Documentation around map() says that it shouldn't ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map ).

我甚至试图创建一个我的数组的克隆来转换我的函数

I even tried to create a clone of my array turning my function like this

const freeProduct = function(products){
    p = products.splice()
    return p.map(x => {x.productType = "free"; return x})
}

但我仍然得到相同的结果(这开始让我发疯)。

But i still get the same result (which starts to drive me crazy).

我会非常感谢任何可以解释我做错的人!

I would be very thankful to anyone who can explain me what i'm doing wrong !

谢谢

推荐答案

您不是在修改原始数组。您正在修改数组中的对象。如果您想避免改变数组中的对象,可以使用 Object.assign 创建一个具有原始属性的新对象以及您需要的任何更改:

You're not modifying your original array. You're modifying the objects in the array. If you want to avoid mutating the objects in your array, you can use Object.assign to create a new object with the original's properties plus any changes you need:

const freeProduct = function(products) {
  return products.map(x => {
    return Object.assign({}, x, {
      productType: "free"
    });
  });
};

2018编辑:

大多数浏览器中,您现在可以使用对象扩展语法而不是 Object.assign 完成此任务:

In most browsers you can now use the object spread syntax instead of Object.assign to accomplish this:

const freeProduct = function(products) {
  return products.map(x => {
    return {
      ...x,
      productType: "free"
    };
  });
};

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

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