Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop

后端 未结 22 1909
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 02:10

In order to duplicate an array in JavaScript: which of the following is faster to use?

###Slice method

var dup_array = original_array.slice();
<         


        
22条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 02:33

    If you want a REAL cloned object/array in JS with cloned references of all attributes and sub-objects:

    export function clone(arr) {
        return JSON.parse(JSON.stringify(arr))
    }
    

    ALL other operations do not create clones, because they just change the base address of the root element, not of the included objects.

    Except you traverse recursive through the object-tree.

    For a simple copy, these are OK. For storage address relevant operations I suggest (and in most all other cases, because this is fast!) to type convert into string and back in a complete new object.

提交回复
热议问题