How to Deep clone in javascript

前端 未结 19 1761
-上瘾入骨i
-上瘾入骨i 2020-11-22 02:06

How do you deep clone a JavaScript object?

I know there are various functions based on frameworks like JSON.parse(JSON.stringify(o)) and $.extend(t

19条回答
  •  一向
    一向 (楼主)
    2020-11-22 03:00

    I noticed that Map should require special treatment, thus with all suggestions in this thread, code will be:

    function deepClone( obj ) {
        if( !obj || true == obj ) //this also handles boolean as true and false
            return obj;
        var objType = typeof( obj );
        if( "number" == objType || "string" == objType ) // add your immutables here
            return obj;
        var result = Array.isArray( obj ) ? [] : !obj.constructor ? {} : new obj.constructor();
        if( obj instanceof Map )
            for( var key of obj.keys() )
                result.set( key, deepClone( obj.get( key ) ) );
        for( var key in obj )
            if( obj.hasOwnProperty( key ) )
                result[key] = deepClone( obj[ key ] );
        return result;
    }
    

提交回复
热议问题