本篇摘要:主要分享了 JS 中常用的几种深复制方法,有来自于vuex``jQuery``JSON``lodash``immutable
中的经典方法,如果有需要,你可以进一步去研究它们的源码。
- 知识点讲解:对象引用与复制
1、使用 vuex
源码中的deepCopy()
方法
/**
* Deep copy the given object considering circular structure.
* This function caches all nested objects and its copies.
* If it detects circular structure, use cached copy to avoid infinite loop.
*
* @param {*} obj
* @param {Array<Object>} cache
* @return {*}
*/
function deepCopy (obj, cache) {
if ( cache === void 0 ) cache = [];
// just return if obj is immutable value
if (obj === null || typeof obj !== 'object') {
return obj
}
// if obj is hit, it is in circular structure
var hit = find(cache, function (c) { return c.original === obj; });
if (hit) {
return hit.copy
}
var copy = Array.isArray(obj) ? [] : {};
// put the copy into cache at first
// because we want to refer it in recursive deepCopy
cache.push({
original: obj,
copy: copy
});
Object.keys(obj).forEach(function (key) {
copy[key] = deepCopy(obj[key], cache);
});
return copy
}
- 参考资源:Vuex源码
2、JSON.parse
和 JSON.stringify
var obj = { a: 1, b: 2 }
var copy = JSON.parse(JSON.stringify(obj))
3、jQuery 中 extend()
const copy = jQuery.extend([deep], target, object1, [objectN])
4、使用 lodash
工具库
import _ from 'lodash'
const b=_.cloneDeep(a)
5、使用 immutable
工具库
import { Map } from 'immutable'
const imA = Map({
username:'马云',
money:150000000000,
info:{ married:true, witticism:'我没见过钱,我对钱不感兴趣' }
})
const imB = Map({
username:'laoxie',
gender:'男',
info:{ married:false, age:18 }
})
const newImData = imA.merge(imB);
console.log(newImData.toJS());
//输出 :
// {
// username:'laoxie',
// gender:'男',
// money:150000000000,
// info:{ married:false, age:18 }
// }
const newImData = imA.mergeDeep(imB);
//输出 :
// {
// username:'laoxie',
// gender:'男',
// money:150000000000,
// info:{ married:false, age:18, witticism:'我没见过钱,我对钱不感兴趣' }
// }
- 资源链接: Immutable.js
6、自己封装深复制方法
function deepClone(target) {
if (typeof (target) !== 'object') {
return target;
}
var result;
if (Object.prototype.toString.call(target) == '[object Array]') {
// 数组
result = []
} else {
// 对象
result = {};
}
for (var prop in target) {
if (target.hasOwnProperty(prop)) {
result[prop] = deepClone(target[prop])
}
}
return result;
}
本篇结束,感谢点赞!!!
网友评论