Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

如何实现深拷贝? #39

Open
Rosamand opened this issue Apr 19, 2018 · 1 comment
Open

如何实现深拷贝? #39

Rosamand opened this issue Apr 19, 2018 · 1 comment

Comments

@Rosamand
Copy link

Rosamand commented Apr 19, 2018

深拷贝的作用在于能够实现对于数组和对象的拷贝,不影响拷贝后数据对原数据造成的影响。
实现函数:
function deepCopy(p,c) { var c=c||{};//容错处理 for(var i in p){ if(typeof p[i]==='object'){//引用类型的数据单独处理 c[i]=(p[i].constructor===Array)?[]:{}; deepCopy(p[i],c[i]);//递归处理引用类型数据 }else{ c[i]=p[i];//值类型的数据直接进行拷贝 } } return c; }
我理解的也不是特别明白,希望各位能够提出一些宝贵的见解
具体的可以参考:https://m.jb51.net/article/91906.htm

@koudingl
Copy link

function deepClone(origin, target) {
        var target = target || {};
        for (var prop in origin) {
            if (origin.hasOwnProperty(prop)) {
                if (typeof origin[prop] == 'object' && typeof origin[prop] !== null) {
                    if (origin[prop] instanceof Array) {
                        target[prop] = [];
                        deepClone(origin[prop], target[prop]);//递归调用deepClone
                    }
                    if (origin[prop] instanceof Object) {
                        target[prop] = {};
                        deepClone(origin[prop], target[prop]);//递归调用deepClone
                    }
                } else if (typeof origin[prop] == 'number' || typeof origin[prop] == 'string' || typeof origin[prop] == 'boolean') {
                    target[prop] = origin[prop];
                }
            }
        }
        return target;
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants