数组深拷贝看起来很简单。
array.concat()就行了。
但是,如果数组里有对象呢?
实际上,你以为你拷贝了对象,但实际上你只拷贝了对象的引用(指针)!
我们可以做个试验。
// test let arr_a = [{a:1,b:2,c:3}, {d:4,e:5,f:6}, {g:7,h:8,i:9}] let arr_b = arr_a.concat() arr_b[2].g = 70 arr_b[3] = null console.log(arr_a,arr_b) // test end
结果:
两边的对象都被改了。而数组B push的时候,数组A不受影响。
这说明数组本身是深拷贝了,但数组里的对象没有深拷贝。
以上。