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

后端 未结 22 1540
佛祖请我去吃肉
佛祖请我去吃肉 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:34

    Take a look at: link. It's not about speed, but comfort. Besides as you can see you can only use slice(0) on primitive types.

    To make an independent copy of an array rather than a copy of the refence to it, you can use the array slice method.

    Example:

    To make an independent copy of an array rather than a copy of the refence to it, you can use the array slice method.

    var oldArray = ["mip", "map", "mop"];
    var newArray = oldArray.slice();
    

    To copy or clone an object :

    function cloneObject(source) {
        for (i in source) {
            if (typeof source[i] == 'source') {
                this[i] = new cloneObject(source[i]);
            }
            else{
                this[i] = source[i];
      }
        }
    }
    
    var obj1= {bla:'blabla',foo:'foofoo',etc:'etc'};
    var obj2= new cloneObject(obj1);
    

    Source: link

提交回复
热议问题