why a js map on an array modify the original array?

前端 未结 4 1778
走了就别回头了
走了就别回头了 2020-12-01 03:09

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

I have an array of objects like this :

const products = [{
    ...,
    \'productType\' = \'premium\',         


        
4条回答
  •  盖世英雄少女心
    2020-12-01 03:24

    To elaborate on SimpleJ's answer - if you were to === the two arrays, you would find that they would not be equal (not same address in memory) confirming that the mapped array is in fact a new array. The issue is that you're returning a new array, that is full of references to the SAME objects in the original array (it's not returning new object literals, it's returning references to the same object). So you need to be creating new objects that are copies of the old objects - ie, w/ the Object.assign example given by SimpleJ.

提交回复
热议问题