Javascript中复制一个数组主要有以下几种方法。
var source = [1, [2, 3]]; var copy1 = [...source], copy2 = source.concat(), copy3 = source.slice(), copy4 = []; Object.assign(copy4, source);
但以上都是浅拷贝,即如果数组中包含数组或对象,则复制的是该数组或对象的地址,也就是只复制了“一层”。如果改变复制后数组内子数组或子对象的值,原数组也会改变,如下。
copy3[1][0] = 3; console.log(source);//[ 1, [ 3, 3 ] ]
思路:当复制数组或对象时,需要遍历其所有子元素。若子元素为数组或对象则继续遍历其子元素的子元素。因此应采用递归的方法实现深拷贝,代码如下。
function deepCopy(source) { //出口条件 if (typeof source !== "object") { return source; } else { var newObj; if (source instanceof Array) { newObj = []; } else { newObj = {}; } for (let i in source) { //i是source的键 if (typeof source[i] !== "object"){ newObj[i] = source[i]; } else { newObj[i] = deepCopy(source[i]); } } return newObj; } }
补充:
typeof返回变量类型,无法区分数组、对象和null(都返回object),NaN和数字(都返回number)。
typeof 1;//number typeof NaN;//number typeof "a";//string typeof true;//boolean typeof [1,2];//object typeof {a: 1};//object typeof null;//object typeof undefined;//undefined function test () {} typeof test;//function