minhuaF / blog

I will write my front-end story.
9 stars 1 forks source link

javascript深拷贝与浅拷贝 #1

Open minhuaF opened 6 years ago

minhuaF commented 6 years ago

javascript 数据类型

基本类型

Undefined, Null, String, Number, Boolean, Symbol

引用类型

Object, Array, Date, RegExp, Function

深拷贝

const deepClone = (source) => {
  if (!source || typeof source !== 'object') {
    throw new Error('error arguments')
  }
  // 判断类型时有的使用 `instanceof`, 这个和 `constructor ` 有什么不一样?
  let targetObj = source.constructor === Array ? [] : {}
  for (let key in source) {
    if (source.hasOwnProperty(key)) {
      if (source[key] && typeof source[key] == 'object') {
        targetObj[key] = source[key].constructor === Array ? [] : {}
        targetObj[key] = deepClone(source[key])
      } else {
        targetObj[key] = source[key]
      }
    }   
  }
  return targetObj
}