/** * 深拷贝 * @param {*} obj 需拷贝的对象 * @returns 深拷贝后的对象 */ function copyObj (obj) { // 对于原始类型和常见的非值,直接返回原来值 if ([NaN, null].includes(obj)) return obj if (['number', 'string', 'boolean', 'null', 'undefined', 'function', 'symbol'].includes(typeof obj)) { return obj } const objCopy = Array.isArray(obj) ? [] : {} for (const key in obj) { objCopy[key] = typeof obj[key] === 'object' ? copyObj(obj[key]) : obj[key] } return objCopy } var obj1 = { name: 'zhangsan', age: 18, details: { like: ['打篮球', '唱歌'], sex: 1, tags: [18, 23] } } var r1 = copyObj(NaN) // NaN console.log(r1) var r1 = copyObj(null) console.log(r1) // NaN var r1 = copyObj(1) console.log(r1) // NaN var r1 = copyObj('test') console.log(r1) // 'test' var r1 = copyObj(true) console.log(r1) // true var r1 = copyObj(undefined) console.log(r1) // undefined var r1 = copyObj(() => { }) console.log(r1) // () => { } var obj2 = copyObj(obj1) console.log('obj2', obj2, `obj1 是否等于 obj2, ${obj1 === obj2}`)