浅拷贝:
var a = [1, 2, 3, 4, 5];
var b = a;
a[0] = 2
console.log(a);
console.log(b);
//因为b浅拷贝a, ab指向同一个内存地址(堆中的值一样)
//b会随着a的变化而变化
//[2, 2, 3, 4, 5]
//[2, 2, 3, 4, 5]
深拷贝:
function deepClone(obj)
{
var
newObj = obj instanceof Array ? []:{};
if
(
typeof
obj !==
'object'
)
{
return
obj;
}
else
{
for
(
var
i
in
obj)
{
newObj[i] =
typeof
obj[i] ===
'object'
? deepClone(obj[i]) : obj[i];
}
}
return
newObj;
}
var
a = [1, 2, 4, 6,
"a"
,
"12"
, [1, 2]];
var
b = deepClone(a);
a[3] = 7;
console.log(a);
console.log(b);
//b对象并没有因为a对象的改变而改变,因为b深拷贝a
[ 1, 2, 4, 7, 'a', '12', [ 1, 2 ] ]
[ 1, 2, 4, 6, 'a', '12', [ 1, 2 ] ]