标签:递归 res 数组 cal cti call 复制 判断 pre
什么是浅拷贝?
借赋值的形式拷贝引用对象,指向的是同一个地址,修改对象是原对象也会修改
什么是深拷贝?
完全拷贝一个新对象,修改对象是原对象不会更改
浅拷贝的几种方案
1) 等号赋值
let apple = { color: ‘red‘}; let newApple = apple;
2) Object.assign()
let apple = { size: { color: ‘red‘ } }; let newApple = Object.assign({}, apple); newApple.size.color = ‘green‘; console.log(newApple.size.color); // green
3) 数组concat方法
let apple = [1, {color: ‘red‘} ]; let newApple = apple.concat(); newApple[1].color = ‘green‘; console.log(apple[1].color) // green
4) 数组的slice方法
let apple = [1, {color: ‘red‘} ]; let newApple = apple.slice(); newApple[1].color = ‘green‘; console.log(apple[1].color) // green
深拷贝的几种方案
1) 对象只有一层时, 可用Object.assign()实现
let apple = { color: ‘red‘ }; let newApple = Object.assign({},apple); newApple.color = ‘green‘; console.log(apple); //{color: ‘red‘}
2) JSON.parse(JSON.stringify())
let apple = [1, {color: ‘red‘} ]; let newApple = JSON.parse(JSON.stringify(apple)); newApple[1].color = "green"; console.log(apple) // 原对象未改变
3) 递归实现一个深拷贝
// 在JavaScript中,想要判断某个对象值属于哪种内置类型,最靠谱的做法就是通过Object.prototype.toString方法. function dataType(value) { return Object.prototype.toString.call(value).slice(8, -1); } function clone(value) { let result, currentType = dataType(value); if (currentType === ‘Object‘) { result = {} } else if (currentType === ‘Array‘) { result = [] } else { return value } for (let i in value) { if (dataType(value[i]) === ‘Object‘ || dataType(value[i]) === ‘Array‘) { result[i] = clone(value[i]) } else { result[i] = value[i] } } return result } var apple = { name: ‘yang‘, list: { id: [1, 2, 4], color: ‘red‘ } } var newApple = clone(apple)
标签:递归 res 数组 cal cti call 复制 判断 pre
原文地址:https://www.cnblogs.com/Tiboo/p/12306442.html