>  기사  >  웹 프론트엔드  >  JavaScript의 객체 전체 복사

JavaScript의 객체 전체 복사

黄舟
黄舟원래의
2016-12-14 09:59:411084검색

객체의 전체 복사와 얕은 복사의 차이점은 다음과 같습니다.

얕은 복사: 객체 자체가 아닌 참조만 복사합니다.
깊은 복사: 모든 객체를 복사합니다. 복사한 개체에서 참조합니다.

1. 얕은 복사 구현

간단한 복사 문만 사용하면 얕은 복사의 구현 방법은 비교적 간단합니다.

1.1 방법 1: 단순 복사문

/* ================ 浅拷贝 ================ */
function simpleClone(initalObj) {
    var obj = {};
    for ( var i in initalObj) {
        obj[i] = initalObj[i];
    }
    return obj;
}

고객 호출

/* ================ 客户端调用 ================ */
var obj = {
    a: "hello",
    b: {
        a: "world",
        b: 21
    },
    c: ["Bob", "Tom", "Jenny"],
    d: function() {
        alert("hello world");
    }
}
var cloneObj = simpleClone(obj); // 对象拷贝
   
console.log(cloneObj.b); // {a: "world", b: 21}
console.log(cloneObj.c); // ["Bob", "Tom", "Jenny"]
console.log(cloneObj.d); // function() { alert("hello world"); }
   
// 修改拷贝后的对象
cloneObj.b.a = "changed";
cloneObj.c = [1, 2, 3];
cloneObj.d = function() { alert("changed"); };
   
console.log(obj.b); // {a: "changed", b: 21} // // 原对象所引用的对象被修改了
   
console.log(obj.c); // ["Bob", "Tom", "Jenny"] // 原对象所引用的对象未被修改
console.log(obj.d); // function() { alert("hello world"); } // 原对象所引用的函数未被修改

1.2 방법 2: Object.sign()

Object.sign() 메서드는 소스 객체의 열거 가능한 속성을 원하는 만큼 대상 객체에 복사한 다음 대상 객체를 반환할 수 있습니다. 하지만 Object.ass() 얕은 복사가 수행되며, 복사되는 것은 개체 자체가 아닌 개체의 속성에 대한 참조입니다.

 
var obj = { a: {a: "hello", b: 21} }; 
var initalObj = Object.assign({}, obj); 
initalObj.a.a = "changed"; 
console.log(obj.a.a); // "changed"

2. Deep Copy 구현

Deep Copy를 구현하는 방법에는 가장 간단한 JSON.parse() 방법과 일반적으로 사용되는 Recursive Copy 방법이 있으며, ES5 Object.create() 메소드.

2.1 방법 1: JSON.parse() 메서드 사용

전체 복사를 구현하는 방법은 다양합니다. 예를 들어 가장 간단한 방법은 JSON.parse()를 사용하는 것입니다.

/* ================ 深拷贝 ================ */
function deepClone(initalObj) {
    var obj = {};
    try {
        obj = JSON.parse(JSON.stringify(initalObj));
    }
    return obj;
}
    
/* ================ 客户端调用 ================ */
var obj = {
    a: {
        a: "world",
        b: 21
    }
}
var cloneObj = deepClone(obj);
cloneObj.a.a = "changed";
   
console.log(obj.a.a); // "world"

이 방법은 간단하고 사용하기 쉽습니다.

그러나 이 방법에는 많은 단점도 있습니다. 예를 들어 객체의 생성자가 삭제된다는 점입니다. 즉, 깊은 복사 후에는 객체의 원래 생성자가 무엇이든 상관없이 깊은 복사 후에는 객체가 됩니다.

이 메서드가 올바르게 처리할 수 있는 유일한 객체는 Number, String, Boolean, Array 및 flat 객체, 즉 json으로 처리할 수 있는 객체입니다. 직접 표현된 데이터 구조입니다. RegExp 개체는 이런 방식으로 전체 복사될 수 없습니다.

2.2 방법 2: 재귀 복사

코드는 다음과 같습니다.

/* ================ 深拷贝 ================ */
function deepClone(initalObj, finalObj) {
    var obj = finalObj || {};
    for (var i in initalObj) {
        if (typeof initalObj[i] === 'object') {
            obj[i] = (initalObj[i].constructor === Array) ? [] : {};
            arguments.callee(initalObj[i], obj[i]);
        } else {
            obj[i] = initalObj[i];
        }
    }
    return obj;
}

위 코드는 실제로 Deep Copy를 구현할 수 있습니다. 그러나 서로 참조하는 두 개체를 만나면 무한 루프가 발생합니다.

객체가 서로 참조하여 발생하는 무한 루프를 방지하려면 순회 중에 객체가 서로 참조하는지 확인하고, 그렇다면 루프를 종료해야 합니다.

개선된 코드는 다음과 같습니다.

/* ================ 深拷贝 ================ */
function deepClone(initalObj, finalObj) {
    var obj = finalObj || {};
    for (var i in initalObj) {
        var prop = initalObj[i];
   
        // 避免相互引用对象导致死循环,如initalObj.a = initalObj的情况
        if(prop === obj) {
            continue;
        }
   
        if (typeof prop === 'object') {
            obj[i] = (prop.constructor === Array) ? [] : {};
            arguments.callee(prop, obj[i]);
        } else {
            obj[i] = prop;
        }
    }
    return obj;
}

2.3 방법 3: Object.create() 메소드 사용

var newObj 직접 사용 = Object.create(oldObj)는 깊은 복사 효과를 얻을 수 있습니다.

/* ================ 深拷贝 ================ */
function deepClone(initalObj, finalObj) {
    var obj = finalObj || {};
    for (var i in initalObj) {
        var prop = initalObj[i];
   
        // 避免相互引用对象导致死循环,如initalObj.a = initalObj的情况
        if(prop === obj) {
            continue;
        }
   
        if (typeof prop === 'object') {
            obj[i] = (prop.constructor === Array) ? [] : Object.create(prop);
        } else {
            obj[i] = prop;
        }
    }
    return obj;
}

3. 참고: jQuery.extend() 메소드 구현

jQuery.js의 jQuery.extend()도 객체의 전체 복사본을 구현합니다. 공식 코드는 참고용으로 아래에 게시되어 있습니다.

공식 링크 주소: https://github.com/jquery/jquery/blob/master/src/core.js.

jQuery.extend = jQuery.fn.extend = function() {
    var options, name, src, copy, copyIsArray, clone,
        target = arguments[ 0 ] || {},
        i = 1,
        length = arguments.length,
        deep = false;
   
    // Handle a deep copy situation
    if ( typeof target === "boolean" ) {
        deep = target;
   
        // Skip the boolean and the target
        target = arguments[ i ] || {};
        i++;
    }
   
    // Handle case when target is a string or something (possible in deep copy)
    if ( typeof target !== "object" && !jQuery.isFunction( target ) ) {
        target = {};
    }
   
    // Extend jQuery itself if only one argument is passed
    if ( i === length ) {
        target = this;
        i--;
    }
   
    for ( ; i < length; i++ ) {
   
        // Only deal with non-null/undefined values
        if ( ( options = arguments[ i ] ) != null ) {
   
            // Extend the base object
            for ( name in options ) {
                src = target[ name ];
                copy = options[ name ];
   
                // Prevent never-ending loop
                if ( target === copy ) {
                    continue;
                }
   
                // Recurse if we&#39;re merging plain objects or arrays
                if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
                    ( copyIsArray = jQuery.isArray( copy ) ) ) ) {
   
                    if ( copyIsArray ) {
                        copyIsArray = false;
                        clone = src && jQuery.isArray( src ) ? src : [];
   
                    } else {
                        clone = src && jQuery.isPlainObject( src ) ? src : {};
                    }
   
                    // Never move original objects, clone them
                    target[ name ] = jQuery.extend( deep, clone, copy );
   
                // Don&#39;t bring in undefined values
                } else if ( copy !== undefined ) {
                    target[ name ] = copy;
                }
            }
        }
    }
   
    // Return the modified object
    return target;
};

이 글은 js의 deep copy 관련 내용을 주로 소개하고 있으며, 그 외 내용은 PHP 중국어 홈페이지(www.php.cn)에서 확인하실 수 있습니다. ) 기사!


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.