function deepClone(targetObject) {
if (typeof targetObject !== 'object') return targetObject;
if (targetObject === null) return null;
if (targetObject instanceof Date) return new Date(targetObject);
if (targetObject instanceof RegExp) return new RegExp(targetObject);
let newObj = new targetObject.constructor();
for(let key in targetObject) {
newObj[key] = typeof targetObject[key] === 'object' ? deepClone(targetObject[key]) : targetObject[key];
}
return newObj;
}
复制代码
附件:javascript 判断各种数据类型
typeof 2 //输出 number
typeof null //输出 object
typeof {} //输出 object
typeof [] //输出 object
typeof (function(){}) //输出 function
typeof undefined // 输出 undefined
typeof '222' // 输出 string
typeof true // 输出 boolean
复制代码
看到这里你肯定会问了:我怎么去区分对象,数组和null呢?
Object.prototype.toString.call
var gettype=Object.prototype.toString
gettype.call('aaaa') //输出 [object String]
gettype.call(2222) //输出 [object Number]
gettype.call(true) //输出 [object Boolean]
gettype.call(undefined) //输出 [object Undefined]
gettype.call(null) //输出 [object Null]
gettype.call({}) //输出 [object Object]
gettype.call([]) //输出 [object Array]
gettype.call(function(){}) //输出 [object Function]
复制代码