问题:
使用JS的函数时,将对象类型的值作为参数传到函数内,且在函数内修改了该参数,导致原值被修改。
原因:
JS函数的参数有两种类型,基本类型和引用类型。传参时会传入一个该值的拷贝,且该拷贝类型为浅拷贝
浅拷贝与深拷贝
首先,浅拷贝和深拷贝都只针对于像Object, Array这样的复杂对象,
区别:浅拷贝只复制对象的第一层属性、深拷贝可以对对象的属性进行递归复制
解决办法:
不在方法里修改引用性参数的值,如果一定要这么做那就创建一个拷贝
创建深拷贝拷贝的方法:
1.自己写
deepCopy (o, c) {
c = c || {}
for (let i in o) {
if (typeof o[i] === 'object') {
// 需要深拷贝
if (o[i].constructor === Array) {
// 数组
console.log('是数组')
c[i] = []
} else {
// 对象
console.log('是对象')
c[i] = {}
}
this.deepCopy(o[i], c[i])
} else {
c[i] = o[i]
}
}
return c
}
2.JQuery的extend()方法
$.extend( [deep ], target, object1 [, objectN ] )
deep表示是否深拷贝,为true为深拷贝,为false,则为浅拷贝
target Object类型 目标对象,其他对象的成员属性将被附加到该对象上。
object1 objectN可选。 Object类型 第一个以及第N个被合并的对象。
示例:
// 期初余额的数据
var insertRow = {
endBalance: $("#beginBalance").val(),
type: "期初余额"
};
printTable(insertRow);
function printTable(insertRow) {
var data = new Array();
newRow = $.extend(true, insertRow.type, insertRow);
newRow.endBalance = insertRowBalance;
data.unshift(newRow);
}
3.使用JSON对象的parse()和stringify()方法
function deepClone(obj){
let _obj = JSON.stringify(obj),
objClone = JSON.parse(_obj);
return objClone
}
let a=[0,1,[2,3],4],
b=deepClone(a);
a[0]=1;
a[2][0]=1;
console.log(a,b);
还有尽量不用全局变量
参考:
https://www.cnblogs.com/echolun/p/7889848.html
https://blog.csdn.net/qq_28978893/article/details/79272422
自己服务器的博客地址:http://www.zhangnlei.cn/article/15