js实现深拷贝

582 阅读2分钟

js中值类型和引用类型

常见值类型

      const a; // undefiend
      const s = 'str';
      const n = 100
      const t = ture
      const s = Symbol('s')

常见的引用类型

      const j = { json: 'name' };
      const a = [1,2,3,4,5];
      const n = null // 特殊的引用类型,指针指向为空的地址
      其中函数深一种比较特殊的引用类型
      function fn(){} // 特殊的引用类型,但是不用于存储数据,所以没有 拷贝,地址函数这么一说

typeof 运算符

识别所有的值类型
识别函数
判断是否是引用类型(至于是哪种引用类型就不行了)
	const a; // undefiend  		typeof a ===>undefiend
    const s = 'str';			typeof s ===>string
    const n = 100				typeof n ===>number
    const t = ture				typeof t ===>boolean
    const s = Symbol('s')		typeof s ===>symbol
    判断函数
    typeof console.log() // function
    typeof function fn(){} // function
    识别引用类型(识别不了,是具体的哪种引用类型)
    typeof null// object
    typeof [1,2,3]; // object
    typeof {x:123}; // object
    

深拷贝和浅拷贝的区别

深拷贝需要处理的事情
1、值类型拷贝
2、引用类型的拷贝
3、日期,正则的拷贝
function deepClone(obj = {}) { 
    // 如果是null或者undefiend 就不进行拷贝
    if (obj === null) return obj;
    // 如果是日期
    if (obj instanceof Date) return new Date(obj);
    // 如果是正则
    if (obj instanceof RegExp) return new RegExp(obj);
    // 可能是对象,普通的值 (如过是函数的话,是不需要深拷贝,毕竟是调用的)
    if (typeof obj !== 'Object') return obj;
    // 初始化返回结果
    let result;
    if(obj instanceof Array){
        result = []
    } else {
        result = {}
    }
    
    for(let key in obj) {
        if(obj.hasOwnProperty(key)) { // 对象是否有这个属性,保证key不是原型上的属性
            // 递归
            result[key] = deepClone(obj[key]);
        }
    }
    return result;
} 

// 调用 deppClone(let a={
    "a":123,
    "b":"123123",
    "arr":[1,23],
    "sjon": {
    "b":"123123",
    "b1":"123123",
    "json": {
        "arr": [1,23],
        "a": {
    "a":"123", "b":"sads"}
    }
    }
    })

但是这只是处理了值类型和引用类型的拷贝

如果遇到了正则和日期这种的呢