JS对象深拷贝的几种方法总结

例:

var obj = {
     
    name: "韩信",
    age: 18,
    skin: [
		{
      id: 0, name: '街头霸王', color: 'yellow' },
		{
      id: 1, name: '飞衡', color: 'red'  }
	]
}

1. for…in遍历拷贝对象

function copy(obj) {
     
    var obj2 = {
     }
    for (var key in obj) {
     
        obj2[key] = typeof obj[key] === "object" ? copy(obj[key]) : obj[key]
    }
    return obj2
}
var obj2 = copy(obj) 
console.log(obj2); // {name: "韩信", age: 18, skin: [{ id: 0, name: '街头霸王', color: 'yellow'  },{ id: 1, name: '飞衡', color: 'red'  }]}
console.log(obj === obj2) // false

2. JSON.stringify/JSON.parse

	var obj2 = JSON.parse(JSON.stringify(obj)) // {name: "韩信", age: 18, skin: [{ id: 0, name: '街头霸王', color: 'yellow'  },{ id: 1, name: '飞衡', color: 'red'  }]}
	console.log(obj === obj2) // false

3. 展开运算符

var obj2 = {
     ...obj}
console.log(obj2) // {name: "韩信", age: 18, skin: [{ id: 0, name: '街头霸王', color: 'yellow'  },{ id: 1, name: '飞衡', color: 'red'  }]}
console.log(obj === obj2)  // false

注意:如果obj是一个数组,使用Array.prototype.concat([])可以克隆一个新的数组

4. 用lodash.js工具函数库的cloneDeep函数

var obj2 = _.cloneDeep(obj);

你可能感兴趣的:(js)