js实现深拷贝

js实现深拷贝
  1. 通过 JSON 对象实现深拷贝
//通过js的内置对象JSON来进行数组对象的深拷贝
function deepClone2(obj) {
  var _obj = JSON.stringify(obj),
    objClone = JSON.parse(_obj);
  return objClone;
}
  1. 使用递归的方式实现深拷贝
    function isArray(obj) {
        if (!Array.prototype.isArray) {
            return Object.prototype.toString.call(obj) === '[object Array]'
        }
        else {
            return Array.isArray(obj)
        }
    }
    function deepClone (obj) {
        let newObj
        if (typeof obj === 'Object') {
            if (isArray(obj)) {
                newObj = []
                for (let i in obj) {
                    newObj.push(deepClone(obj[i]))  
                }
            } else if (obj === null) {
                newObj = null
            } else if (obj.constructor === RegExp) {
                newObj = obj
            } else {
                newObj = {}
                for (let i in obj) {
                    newObj[i] = deepClone(obj[i])
                }
            }
        } else {
            newObj = obj
        }
        return newObj
    }
  1. Object.assign()拷贝
当对象中只有一级属性,没有二级属性的时候,此方法为深拷贝,但是对象中有对象的时候,此方法,在二级属性以后就是浅拷贝。
原文地址:https://www.cnblogs.com/fenfen/p/13650365.html