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

JS 实现 deepCopy #46

Open
xuya227939 opened this issue Mar 12, 2019 · 0 comments
Open

JS 实现 deepCopy #46

xuya227939 opened this issue Mar 12, 2019 · 0 comments
Labels

Comments

@xuya227939
Copy link
Owner

xuya227939 commented Mar 12, 2019

function getType(obj) {
    // 为啥不用typeof? typeof无法区分数组和对象
    if(Object.prototype.toString.call(obj) == '[object Object]') {
        return 'Object';
    }

    if(Object.prototype.toString.call(obj) == '[object Array]') {
        return 'Array';
    }
    return 'nomal';
};

function deepCopy(obj) {
    if (getType(obj) == 'nomal') {
        return obj;
    } else {
        var newObj = getType(obj) == 'Object' ? {} : [];
        for(var key in obj) {
            // 为啥要用hasOwnProperty?不需要从对象的原型链上进行复制
            if(obj.hasOwnProperty(key)) {
                newObj[key] = deepCopy(obj[key]);
            }
        }
    }
    return newObj;
}


var object = [
  {
    title: 'test',
    checked: false
  }
];

deepCopy(object);
@xuya227939 xuya227939 added the JS label Jun 26, 2019
@xuya227939 xuya227939 changed the title js实现deepCopy JS实现deepCopy Mar 10, 2020
@xuya227939 xuya227939 changed the title JS实现deepCopy JS 实现 deepCopy Feb 19, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant