数据处理之深浅拷贝完全剖析

大家好 !!!    又到了讨论代码的欢乐时光

深浅拷贝作为面试必考的一个知识点,我们要把它按在地上摩擦

首先 , 我们要了解一个前提,

 

原始值 如 number , string,  boolean , null, undefined是存在栈内存中

引用值如  object   是存在堆内存中,

 

为什么 原始值存在栈内存中呢 ?  因为原始类型占据的空间是固定的,

把它们存在较小的内存区域 -- 栈 中, 方便迅速查询变量的值。

 

由于引用值的一些增删操作会改变引用值的大小, 所以不能把引用值放在栈

内存中,否则会降低变量的查询速度,但是引用值的地址大小是不变的,所以

引用值的地址是存在栈内存中,

 

所以直接把一个引用值赋值给一个变量, 赋的是引用值的地址

const a = {
    0 : 'eat',
    1 : 'run'
};
const b = a;

b[0] = 'change';
console.log(a[0]); // change

把a的赋给b,      a,b指向同一个地址,   所以改变b[0]的值, a[0]的值也发生了变化。

那我们要把a 的 值赋 给 b  同时  不让a, b产生关系应该怎么做呢?

最容易想到的方法, 遍历a,    把a的属性一个一个赋给b

const a = {
    0 : 'eat',
    1 : 'run'
};
const b = {

};
for (let i in a) {
    b[i] = a[i]
}
console.log(b);   // {0: "eat", 1: "run"}
b[0] = 'change';
console.log(a[0]);  // eat

这就是所谓的浅拷贝,又叫做首层深拷贝,

 因为如果 a 的属性 值 里 有 引用值的话 ,直接赋值的话还是赋的地址  ,a 和 b 还是有关联 , 拷贝的不够彻底, 所以叫浅拷贝,

我们先把上面的遍历方法抽成一个myClone方法

const a = {
    0 : 'eat',
    1 : 'run'
};
function myClone(target) {
    if (typeof  target !== 'object') {return}    // 只拷贝对象和数组
    const result = target instanceof Array ? [] : {};  // 新建一个对象或者数组
    for (let key in target) { // 遍历赋值
        result[key] = target[key];
    }
    return result
}
const b = myClone(a);
console.log(b);   // {0: "eat", 1: "run"}
b[0] = 'change';
console.log(a[0]);  // eat

这是教科书式的浅拷贝  ,  数组有特有的浅拷贝方法   :

  

const a = [1, 2, 3, 4, 5];

const b = a.concat();

const c = [].concat(a);

const d = a.slice();

console.log(b);  // (5) [1, 2, 3, 4, 5]

console.log(c);  // (5) [1, 2, 3, 4, 5]

console.log(d); // (5) [1, 2, 3, 4, 5]

 对象也有简单的浅拷贝方法

const me = {
    'look': 'handsome',
};

const you = Object.assign({},me);

console.log(you);  // {look: "handsome"}

you.look = 'ugly';

console.log(me); //  {look: "handsome"}

注意, Object.assign第一个参数一定要传一个空对象, 这样你的丑就和我无关,我依然帅气,否则:

const me = {
    'look': 'handsome',
};

const you = Object.assign(me);

console.log(you);  // {look: "handsome"}

you.look = 'ugly';

console.log(me); //  {look: "ugly"}

你的丑陋把我也带偏了!!!!!!

 

那如何实现有多层嵌套引用值的深拷贝呢?

1    我工作中用的最多的就是。。。。

const me = {
    'look': 'handsome',
    'face' : {
        'eyes' : 'big',
        'mouse': 'small'
    }
};

const you = JSON.parse(JSON.stringify(me));

console.log(you);  // {look: "handsome", face: {eyes: "none", mouse: "small"}}

you.face.eyes = 'none';

console.log(me); //  {look: "handsome", face: {eyes: "big", mouse: "small"}}

这样虽然你的眼睛没了,我的依旧是卡姿兰大眼睛。

这种方法虽然方便,但也有局限性 : 1 属性值为function 或者  undefined 时会被忽略    2  正则表达式会被序列化成一个空对象

const me = {
    'look': 'handsome',
    'face' : {
        'eyes' : 'big',
        'mouse': 'small'
    },
    'eat' : function () {
        console.log('小心吃胖')
    },
    'reg' : /\d+[\w]/g,
    'xxx' : undefined
};

const you = JSON.parse(JSON.stringify(me));

console.log(you);

console.log(me);

输出结果: 

you 中没有了eat 方法 和  xxx 属性 且 reg 变成了 {} ,  解决办法, 利用 JSON.stringify的第二个参数 把它们转成字符串再序列化

const me = {
    'look': 'handsome',
    'face' : {
        'eyes' : 'big',
        'mouse': 'small'
    },
    'eat' : function () {
        console.log('小心吃胖')
    },
    'reg' : /\d+[\w]/g,
    'xxx' : undefined
};
function replace (key, value) {
    if (typeof value === 'function') {
        return value.toString()
    }
    if (typeof  value === 'undefined') {
        return 'undefined'
    }
    return value
}
const you = JSON.parse(JSON.stringify(me, replace));

console.log(you);

console.log(me);

输出结果:

这样 undefined 和 function  也能  拷贝了,  正则表达式大家也可以写一个方法来判断是否是正则表达式,是就也转成字符串

 

2   利用第三方库中的深拷贝方法, 比如 :在jQuery中可以通过添加一个参数来实现递归extend,调用$.extend(true, {}, ...)就可以实现一个深拷贝。

 

3   教科书式的 递归  深拷贝  :

const me = {
    'look': 'handsome',
    'face' : {
        'eyes' : 'big',
        'mouse': {
            'tooth': 'white'
        }
    },
    'eat' : function () {
        console.log('小心吃胖')
    },
    'reg' : /\d+[\w]/g,
    'xxx' : undefined
};
function  isObj(target) {
    if (Object.prototype.toString.call(target) === '[object Array]' || Object.prototype.toString.call(target) === '[object Object]'){
        return true
    } else {
        return false
    }
}
function deepClone (target) {
    // 只拷贝数组和对象, 原始值直接返回
    if (!isObj(target)) {
        return target
    }
    // 存数据的变量
    const result = Array.isArray(target) ? [] : {};
    for (const key in target) {
        // 判断是否是自身的属性,而不是继承自原型链的属性
        if (target.hasOwnProperty(key)) {
            result[key] = isObj(target[key]) ? deepClone(target[key]) : target[key];
        }
    }
    return result

}
const you = deepClone(me);
console.log(you);

console.log(me);

结果 :

所有属性完美拷贝过来了有没有? 简直就是copy忍者卡卡西 啊 ............ 而且两者之间不互相影响

 

你学会了吗🐒🐒🐒🐒🐒🐒

posted @ 2019-03-29 17:31  初心,你好吗  阅读(419)  评论(1编辑  收藏  举报