有一次在操作数据时发现,直接操作原始数据进行赋值,会导致原始数据中的其他项数据也跟着一块改变。排查过后发现是拷贝数据问题,需要深拷贝一份数据,对拷贝的数据进行操作就没问题了,在此记录一下。
深拷贝
cloneObj : function(obj){
var str, newobj = obj.constructor === Array ? [] : {};
if(typeof obj !== 'object'){
return;
}else {
for(var i in obj){
newobj[i] = typeof obj[i] === 'object' && obj[i] !== null ?this.cloneObj(obj[i]) : obj[i];
}
}
return newobj;
},
刚开始使用this.text = txt.replace(/\n/g,'<br>');
发现没有效果,最后参考别人的写法后才发现要使用双斜杠才能准确的匹配出来,大家使用的时候可以注意一下。
后台换行符替换
this.text = txt.replace(/\\n/g,'<br>');