对象赋值:
1.var objOld = {a:1,b:2},
objNew = objOld;
objOld.a = 5;
此时输出:objOld = {a:5,b:2};
objNew = {a:5,b:2};
说明修改objNew 的值会影响objOld 的值
2.var objOld = {a:1,b:2},
objNew = Object.assign({},objOld);
objOld.a = 5;
此时输出:objOld = {a:5,b:2};
objNew = {a:1,b:2};
说明修改objNew 的值不会影响objOld 的值,但是此方法只能修改第一层的 值,深层修改就不可以了,如:var objOld = {a:1,b:{c:2}}, objOld.b.c = 5;
此时输出:objOld = {a:1,b:{c:5}};
objNew = {a:1,b:{c:5}};
3.var objOld = {a:1,b:{c:2}},
objNew = JSON.parse(JSON.stringify(objOld ));
objOld.b.c = 5;
此时输出:objOld = {a:1,b:{c:5}};
objNew = {a:1,b:{c:2}};
说明此对象深层修改,也不会修改原对象的值
数组赋值:
1.var arrOld = [1],
arrNew = arrOld ;
arrNew [0]++;
此时输出:arrOld = [2];
arrNew = [2];
修改arrNew 的值会影响arrOld的值
2.不影响旧值的三种方法:
(1)jquery可以用的方法:
var arrOld = [1],
arrNew = $.extend(true,{},arrOld );
arrNew [0]++;
此时输出:arrOld = [1];
arrNew = [2];
(2)var arrOld = [1],
arrNew = arrOld .concat();
arrNew [0]++;
此时输出:arrOld = [1];
arrNew = [2];
(2)调用函数方法:
var arrOld= [1,2],
arrNew = [3,4];
function change(){
arrOld[0] = 4;
var c = arrOld;
arrOld = arrNew ;
arrNew = c;
}
此时输出:arrOld = [4,2];
arrNew = [3,4];