判断类型(通用类型检测方法)
const isTypeOf = (data) => { return Object.prototype.toString.call(data).replace(/[object (w+)]/, '$1').toLowerCase() } console.log(isTypeOf({})) // object console.log(isTypeOf([])) // array console.log(isTypeOf("ss")) // string console.log(isTypeOf(1)) // number console.log(isTypeOf(false)) // boolean console.log(isTypeOf(/w+/)) // regexp console.log(isTypeOf(null)) // null console.log(isTypeOf(undefined)) // undefined console.log(isTypeOf(Symbol("id"))) // symbol console.log(isTypeOf(() => { })) // function
手写深拷贝
//简单版深拷贝(不考虑Math()和Date()) function deepClone(obj){ //判断是否是对象 function isObject(o){ return (typeof o === 'object' || typeof o === 'function') && typeof o !== null } // 如果obj不是对象,抛出错误 if(!isObject(obj)){ throw new Error('非对象') } //判断是否是数组 let isArray = Array.isArray(obj) //浅拷贝当前obj给newObj let newObj = isArray? [...obj]:{...obj} //对newObj中的key的值挨个进行判断,如果是对象进行递归 Reflect.ownKeys(newObj).forEach(key => { newObj[key] = isObject(obj[key]) ? deepClone(obj[key]) : obj[key] }) //最后记得return newObj return newObj } let obj = { a: [1, 2, 3], b: { c: 2, d: 3 } } let newObj = deepClone(obj) console.log(newObj) newObj.b.c = 1 console.log(obj.b.c) // 2