js 深度克隆
function deepClone(obj) { if (typeof obj !== 'object' || obj === null) { return obj } const result = Array.isArray(obj) ? [] : {} Object.setPrototypeOf(result, Object.getPrototypeOf(obj)) for (const key in obj) { if (obj.hasOwnProperty(key)) { result[key] = deepClone(obj[key]) } } return result } const obj1 = { a: 12, 'b': [12, 232], c: { age: 12, name: 'howhy' } } console.log(deepClone(obj1))
function deepClone(origin, target) { var target = target || {} for (var key in origin) { if (origin.hasOwnProperty(key)) { var item = origin[key] if (item !== null && typeof item == 'object') { if (Object.prototype.toString.call(item) === '[object Array]') { target[key] = [] } else if (Object.prototype.toString.call(item) === '[object Object]') { target[key] = {} } deepClone(item, target[key]) } else { target[key] = item } } } return target } tar = deepClone(ori)