JavaScript의 객체 전체 복사

黄舟
풀어 주다: 2017-02-21 12:00:33
원래의
1074명이 탐색했습니다.



JavaScript에서는 객체를 복사하는 것이 일반적입니다. 그러나 간단한 복사 문은 객체의 얕은 복사본만 만들 수 있습니다. 즉, 참조가 참조하는 객체가 아닌 참조가 복사됩니다. 원래 객체가 의도치 않게 수정되는 것을 방지하기 위해 객체의 전체 복사본을 만들고 싶어하는 경우가 더 많습니다.

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

  • 얕은 복사: 객체의 참조만 복사합니다. 개체 자체가 아닌 개체

  • 전체 복사: 복사된 개체가 참조하는 모든 개체를 복사합니다.

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.ass()

Object.sign() 메서드는 소스 객체를 원하는 만큼 할당할 수 있습니다. 자신의 열거 가능한 속성을 대상 개체에 추가한 다음 대상 개체를 반환합니다. 그러나 Object.sign()은 객체 자체가 아닌 객체의 속성에 대한 참조를 복사하는 단순 복사를 수행합니다.

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() 메서드, 일반적으로 사용되는 재귀 복사 메서드, 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()도 객체의 전체 복사본을 구현합니다. 공식 코드는 참고용으로 아래에 게시되어 있습니다.

공식 링크 주소: http://www.php.cn/.

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;
};
로그인 후 복사


위는 JavaScript의 객체 Deep Copy 내용입니다. 더 자세한 내용은 PHP 중국어를 참고해주세요. 홈페이지(www.php.cn)!






관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!