深拷贝

深拷贝: 

const isType = type => val => type === Object.prototype.toString.call(val).slice(8, -1)
const isArray = isType('Array')
const isObject = isType('Object')
function deepCopy (obj) {
    if(!(isArray(obj)|| isObject(obj))) { return obj }  // 数字、日期、正则、函数、字符串、undefined、null、Symbol直接返回
    const res = isArray(obj) ? [] : {}
    return Object.keys(obj).reduce((prev, item) => {
      prev[item] = (isArray(obj[item]) || isObject(obj[item])) ? deepCopy(obj[item]) : obj[item]
      return prev
    }, res)
}
  •  测试:
const obj1 = {
    name:'Tom',
    age:20,
    school:{
        name: 'XXX第一中学',
        createTime: new Date('1998/01/23')
    },
    family:['father', 'mother', 'Tom']
}
const obj2 = deepCopy(obj1)

 

posted @ 2020-05-04 09:00  进心进利  阅读(150)  评论(0编辑  收藏  举报