答:
JavaScript
中存在两⼤数据类型:
- 基本类型
- 引⽤类型
基本类型数据保存在在栈内存中
引⽤类型数据保存在堆内存中,引⽤数据类型的变量是⼀个指向堆内存中实际对象的引⽤,存在栈中
浅拷⻉:
浅拷⻉,指的是创建新的数据,这个数据有着原始数据属性值的⼀份精确拷⻉,如果属性是基本类型,拷⻉的就是基本类型的值。如果属性是引⽤类型,拷⻉的就是内存地址 ,即浅拷⻉是拷⻉⼀层,深层次的引⽤类型则共享内存地址
下⾯简单实现⼀个浅拷⻉:
function shallowClone(obj) {
const newObj = {};
for(let prop in obj) {
if(obj.hasOwnProperty(prop)){
newObj[prop] = obj[prop];
}
}
return newObj;
}
在
JavaScript
中,存在浅拷⻉的现象有:
- Object.assign
- Array.prototype.slice() , Array.prototype.concat()
- 使⽤拓展运算符实现的复制
Object.assign
var obj = {
age: 18,
nature: ['smart', 'good'],
names: {
name1: 'fx',
name2: 'xka'
},
love: function () {
console.log('fx is a great girl')
}
}
var newObj = Object.assign({}, fxObj);
slice()
const fxArr = ["One", "Two", "Three"]
const fxArrs = fxArr.slice(0)
fxArrs[1] = "love";
console.log(fxArr) // ["One", "Two", "Three"]
console.log(fxArrs) // ["One", "love", "Three"]
concat()
const fxArr = ["One", "Two", "Three"]
const fxArrs = fxArr.concat()
fxArrs[1] = "love";
console.log(fxArr) // ["One", "Two", "Three"]
console.log(fxArrs) // ["One", "love", "Three"]
拓展运算符
const fxArr = ["One", "Two", "Three"]
const fxArrs = [...fxArr]
fxArrs[1] = "love";
console.log(fxArr) // ["One", "Two", "Three"]
console.log(fxArrs) // ["One", "love", "Three"]
深拷⻉
深拷⻉开辟⼀个新的栈,两个对象属完成相同,但是对应两个不同的地址,修改⼀个对象的属性,不会 改变另⼀个对象的属性
常⻅的深拷⻉⽅式有:
- _.cloneDeep()
- jQuery.extend()
- JSON.stringify()
- ⼿写循环递归
_.cloneDeep()
const _ = require('lodash');
const obj1 = {
a: 1,
b: { f: { g: 1 } },
c: [1, 2, 3]
};
const obj2 = _.cloneDeep(obj1);
console.log(obj1.b.f === obj2.b.f);// false
jQuery.extend()
const $ = require('jquery');
const obj1 = {
a: 1,
b: { f: { g: 1 } },
c: [1, 2, 3]
};
const obj2 = $.extend(true, {}, obj1);
console.log(obj1.b.f === obj2.b.f); // false
JSON.stringify()
const obj2=JSON.parse(JSON.stringify(obj1));
但是这种⽅式存在弊端,会忽略
undefined
、
symbol
和
函数
const obj = {
name: 'A',
name1: undefined,
name3: function() {},
name4: Symbol('A') }
const obj2 = JSON.parse(JSON.stringify(obj));
console.log(obj2); // {name: "A"}
循环递归
function deepClone(obj, hash = new WeakMap()) {
if (obj === null) return obj; // 如果是null或者undefined我就不进⾏拷⻉操作
if (obj instanceof Date) return new Date(obj);
if (obj instanceof RegExp) return new RegExp(obj);
// 可能是对象或者普通的值 如果是函数的话是不需要深拷⻉
if (typeof obj !== "object") return obj;
// 是对象的话就要进⾏深拷⻉
if (hash.get(obj)) return hash.get(obj);
let cloneObj = new obj.constructor();
// 找到的是所属类原型上的constructor,⽽原型上的 constructor指向的是当前类本身
hash.set(obj, cloneObj);
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
// 实现⼀个递归拷⻉
cloneObj[key] = deepClone(obj[key], hash);
}
}
return cloneObj;
}
深考贝
// 深拷贝 @param {Object} obj 要拷贝的对象
function deepClone(arg) {
if (typeof arg!== 'object' || arg== null) {
// arg 是 null ,或者不是对象和数组,直接返回
return arg
}
// 初始化返回结果
let result
if (arg instanceof Array) {
result = []
} else {
result = {}
}
for (let key in arg) {
// 保证 key 不是原型的属性
if (arg.hasOwnProperty(key)) { // 检测key是不是arg的私有属性
// 递归调用!!!
result[key] = deepClone(arg[key])
}
}
// 返回结果
return result
}