javascript深拷贝
// 检测数据类型 var typeString = (obj) => { var cons = Object.prototype.toString.call(obj).slice(8, -1); return (cons === 'Array' || cons === 'Object') } // 深度克隆 var deepClone = (oldObj) => { if (typeString(oldObj)) { var newObj = oldObj.constructor(); //[] for (let i in oldObj) { //遍历属性 //如果数据类型仍为Array||Object则递归,反之为新的对象赋值 newObj[i] = typeString(oldObj[i]) ? deepClone(oldObj[i]) : oldObj[i] } return newObj; } else { return oldObj } }
// 测试
var o1 = [1, 2, [3, 4]]
var o2 = deepClone(o1)
console.log(o1 === o2) // false
o1[2][0] = 2019
console.log(o2) // [1, 2, [3, 4]]
console.log(o1) // [1, 2, [2019, 4]]