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

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

问题描述

我对map()的行为很困惑.

I'm quite confused by the behavior 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", ...]

所以我将函数改写为:

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()周围的文档说不应(

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 into 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天全站免登陆