2025年|某些常用的代码题 Arieslx 2025-10-29 2025 浅拷贝和深拷贝12345678//浅拷贝const copy1 = {...obj};const copy2 = Object.assign({}, obj)const copy3 = arr.slice();const copy4 = Array.from(arr) 123456789101112131415161718//深拷贝const deepCopy1 = JSON.parse(JSON.stringify(obj))const deepClone(obj){ if(obj===null || typeof obj !== 'object') return obj; if(obj instanceof Date) return new Date(obj); if(obj instanceof Array) return obj.map(item => deepClone(item)); const cloned = {}; for(let key in obj){ if(obj.hasOwnProperty(key)){ cloned[key] = deepClone(obj(key)) } } return cloned}const deepCopy3 = _.cloneDeep(obj) JSON方法深拷贝的局限性12345678910111213const obj = { date: new Date(), // 会被转为字符串 func: function() {}, // 会被丢失 undefined: undefined, // 会被丢失 infinity: Infinity, // 会被转为 null regexp: /pattern/, // 会被转为空对象 symbol: Symbol('foo'), // 会被丢失 // 循环引用会导致错误};// 循环引用问题obj.self = obj;JSON.parse(JSON.stringify(obj)); // 报错:Converting circular structure to JSON