Object.assign保持对原始对象的引用
这个问题在这里已经有了答案:
事实上,这可以通过不同的方式完成:
deep=true
): function cloneObj(obj, deep=false){
var result = {};
for(key in obj){
if(deep && obj[key] instanceof Object){
if(obj[key] instanceof Array){
result[key] = [];
obj[key].forEach(function(item){
if(item instanceof Object){
result[key].push(cloneObj(item, true));
} else {
result[key].push(item);
}
});
} else {
result[key] = cloneObj(obj[key]);
}
} else {
result[key] = obj[key];
}
}
return result
}
// Shallow copy
var newObject = cloneObj(oldObject);
// Deep copy
var newObject = cloneObj(oldObject, true);
// Shallow copy
var newObject = jQuery.extend({}, oldObject);
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
// Shallow copy
var newObject = _.clone(oldObject);
PS:我用以下数据测试了我的功能并且工作正常:
var oldObject = {a:1, b:{d:2,c:6}, c:[1,2,{t:1}]};
newObject= cloneObj(oldObject, true);
newObject['b']['d']=8;
newObject['a']=8;
newObject['c'][2]['t']=5;
console.log(oldObject)
console.log(newObject)
链接地址: http://www.djcxy.com/p/24769.html