How to clone a Javascript Array of Objects?

后端 未结 7 1337
一向
一向 2020-12-09 19:10

I have a result set which is an array of objects. I need to clone this so I can make changes to it, without touching the original data.

var data = w2ui.grid.         


        
7条回答
  •  时光取名叫无心
    2020-12-09 19:54

    This is because an array is held as a pointer, so setting a new variable just points to the same array.

    The easiest way I know of is with slice...

    var data = w2ui.grid.records.slice(0);
    

    This creates a new array with all of the original values in, because you're slicing from the first one (0).

    If you need a deep clone, because your array contains objects/arrays too, try this...

    https://github.com/pvorb/clone

提交回复
热议问题