js 深度克隆

howhy發表於2024-04-28
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))

相關文章