Js 对象拷贝

时间:2020-05-01

浅拷贝

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    /**
     * 拷贝对象,浅拷贝,改变原对象会影响到目标对象
     * @param srcObj 原对象
     * @param destObj 目标对象
     */
    function copyObj(srcObj, destObj) {
        for (var i in srcObj) {
            destObj[i] = srcObj[i];
        }
    }

    var srcObj = {
        'name': '李四',
        'age': 28,
        'data': {
            'address': '湖北武汉'
        },
        'arr': [1, 2, 3, 4, 5]
    };

    var destObj = {};
    copyObj(srcObj, destObj);
    srcObj.data.address = '湖北孝感';
    srcObj.arr[0] = 10;
    console.dir(destObj);
</script>
</body>
</html>

深拷贝

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    /**
     * 拷贝对象,深拷贝,改变原对象不会影响到目标对象
     * @param srcObj 原对象
     * @param destObj 目标对象
     */
    function copyObj(srcObj, destObj) {
        for (var i in srcObj) {
            var val = srcObj[i];
            if (val instanceof Object) {
                // 对象
                destObj[i] = {};
                copyObj(val, destObj[i]);
            } else if (val instanceof Array) {
                // 数组
                destObj[i] = [];
                copyObj(val, destObj[i]);
            } else {
                // 其它数据
                destObj[i] = srcObj[i];
            }
        }
    }

    var srcObj = {
        'name': '李四',
        'age': 28,
        'data': {
            'address': '湖北武汉'
        },
        'arr': [1, 2, 3, 4, 5]
    };

    var destObj = {};
    copyObj(srcObj, destObj);
    srcObj.data.address = '湖北孝感';
    srcObj.arr[0] = 10;
    console.dir(destObj);
</script>
</body>
</html>