web 深拷贝

114 阅读1分钟

数据类型

JS 中共有 8  种基础的数据类型,分别为: Undefined 、 Null 、 Boolean 、 Number 、 String 、 Object 、 Symbol 、 BigInt

数据类型判断

typeof:能判断所有值类型,函数。不可对 null、对象、数组进行精确判断,因为都返回 object, 能判断 funtion

instanceof:能判断对象类型,不能判断基本数据类型,其内部运行机制是判断在其原型链中能否找到该类型的原型

Object.prototype.toString.call() :所有原始数据类型都是能判断的,还有 Error 对象,Date 对象

如何判断变量是否为数组

Array.isArray(arr); // true 
arr instanceof Array; // true 
Object.prototype.toString.call(arr); // "[object Array]"

深拷贝 代码实现

  1. 获取数据类型 Object.prototype.toString.call()

  2. 'Array' || 'Object' || 'Map' || 'Set', 需要遍历拷贝, 否则直接返回

3.Array 或 Object 或 Map 或 Set, 统一创建新的实例

new target.constructor()

4. Array 或 Object 或 Map 或 Set,遍历 递归复制。 forEach 函数

性能 while > for in > for
function cloneObject(target) {
    const type = getType(target)
    if (!isCopy(type)) return target;	
    
    const clone_target = new target.constructor()
        
    if (type == 'Object') {
	const t_arr = Object.keys(target)
	t_arr.forEach(key => {
            clone_target[key] = cloneObject(target[key])
	})
    }
				
    if (type == 'Array') {
	target.forEach((value, index) => {
            clone_target[index] = cloneObject(value)
	})
    }
    
    if (type == 'Map') {
	target.forEach((value, key) => {
            clone_target.set(key, cloneObject(value))
	})
    }
    
    if (type == 'Set') {
	target.forEach((value) => {
            clone_target.add(cloneObject(value))
	})
    }
    
    return clone_target
}
			
function getType(target) {
    const type_str = Object.prototype.toString.call(target)
    const t_arr = type_str.split(' ')
    const type = t_arr[1].slice(0, -1)
    return type
}
			
function isCopy(type) {
    return type === 'Array' || type === 'Object' || type === 'Map' || type === 'Set'
}
			
const target =  {
    field1: 1,
    field2: undefined,
    field3: {
	child: 'child'
    },
    field4: [2, 4, 8]
}
			
console.log(cloneObject(target))