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

2020/04.18 - 实现深拷贝函数(简单版) #4

Open
Jitianpeng opened this issue Apr 17, 2020 · 0 comments
Open

2020/04.18 - 实现深拷贝函数(简单版) #4

Jitianpeng opened this issue Apr 17, 2020 · 0 comments

Comments

@Jitianpeng
Copy link
Owner

Jitianpeng commented Apr 17, 2020

至于为啥是==简单版==,复杂版的我不会啊:joy:

深拷贝 浅拷贝 赋值 的区别在哪?

  • 赋值: 当我们把一个对象赋值给一个新变量的时候,赋的其实是该对象在栈中的地址,而不是堆中的数据
  • 浅拷贝: 他会创建一个对象,如果属性是基本类型的值,拷贝的就是基本类型的值,如果是引用类型,拷贝的就是内存地址.
  • 深拷贝: 他会创建一个对象,里面的递归把里面的值拷贝到新对象中.

忘记在哪弄的图了,如果有谁看到麻烦评论下我补上

// target: 目标对象,被赋值的对象
function clone(target) {
    // 判断一下对象是不是引用类型(数组和对象)
    if (typeof target === 'object') {
        // 判断下 target 到底是数组还是对象,同时赋默认值
        let cloneTarget = Array.isArray(target) ? [] : {};
        // 循环遍历 target
        for (const key in target) {
            // 走递归函数
            cloneTarget[key] = clone(target[key]);
        }
        // 返回
        return cloneTarget;
    } else if(typeof target === 'function') {
        // 如果是 函数的话你懂得.
        return eval('(' + target.toString() + ')')
    } else {
        // 如果是基本类型的值直接 return
        return target;
    }
};
var data = {
    name: '123',
    age: 15,
    data: {
        name: '大壮',
        age: 19
    },
    add: function() {}
}
console.log(clone(data))
/**
    {
        name: '123',
        age: 15,
        data: { name: '大壮', age: 19 },
        add: [Function]
    }
 */

上面代码中,为了避免不理解,我直接截个图方便理解

好了.简单版就是这个样子.

复杂版的:

请慢慢食用,小心噎着(^▽^)

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

1 participant