js深拷贝,不包括原型链

1、利用JavaScript 值和 JSON 字符串的相互转换

const new = JSON.parse(JSON.stringify(old))

 

2、利用递归来实现每一层都重新创建对象并赋值

    function copy(val) {
      const result = Object.prototype.toString.call(val) === '[object Object]' ? {} : []
      for (let key in val) {
        let value = val[key]
        if (Object.prototype.toString.call(value) === '[object Object]' || 
            Object.prototype.toString.call(value) === '[object Array]') {
          result[key] = copy(value)
        } else {
          result[key] = value
        }
      }
      return result
    }

 

你可能感兴趣的:(js深拷贝,不包括原型链)