主要考察目标:
- 数据类型校验
- 循环引用
function deepClone(data, hash = new WeakMap) {
if (data == undefined) return data;
if (typeof data !== 'object') return data;
if (data instanceof RegExp) return new RegExp(data)
if (data instanceof Date) return new Date(data)
var v = hash.get(data)
if (v) return v
var instance = new data.constructor
hash.set(data, instance)
for (var key in data) {
if (data.hasOwnProperty(key)) {
instance[key] = deepClone(data[key], hash)
}
}
return instance
}
var a = {
name: 'bob',
desc: {
age: 12
}
}
var b = deepClone(a)
b.desc.age = 100
console.log(b)
console.log(a)
// js循环引用
var t = {}
t.t = t
console.log(deepClone(t))
今日查看Vuex源码,工具函数中定义了一个deepCopy函数,也可以达到深克隆效果,只考虑了对数组和对象类型进行深拷贝,不过用于日常的业务功能开发,肯定足够了。
function find(list, fn) {
return list.filter(fn)[0]
}
function deepCopy(obj, cache = []){
if(obj === null || typeof obj !== 'object'){
return obj
}
const hit = find(cache, v => v.original === obj)
if(hit){
return hit.copy
}
const copy = Array.isArray(obj) ? [] : {}
cache.push({
original: obj,
copy
})
Object.keys(obj).forEach(key => {
copy[key] = deepCopy(obj[key], cache)
})
return copy
}