js 数组的深浅拷贝

来源:互联网 发布:淘宝 中国质造 编辑:程序博客网 时间:2024/05/23 01:23

数组的浅拷贝与深拷贝
浅拷贝只复制第一层,深拷贝全部复制

浅拷贝:

// es6const arr1 = [1, 2, 3, [4, 5, 6]];const [...arr2] = arr1;// es5 var arr1 = [1, 2, 3, [4, 5, 6]];var arr2 = arr1.slice();arr2.push(7);arr2[3].push(7);arr1 // [1, 2, 3, [4, 5, 6, 7]];arr2 // [1, 2, 3, [4, 5, 6, 7], 7];

深拷贝(需使用递归):

const arrayDeep = (targetArray) => {    const array = [];    targetArray.map(item => {           if(Object.prototype.toString.call(item) === '[object Object]') {            const obj = {};            for(let i in item) {                obj[i] = item[i];                // 对象属性为数组                if(Object.prototype.toString.call(item[i]) === '[object Array]') {                    obj[i] = arrayDeep(item[i]);                    }            }            array.push(obj);        }else if(Object.prototype.toString.call(item) === '[object Array]') {            //多维数组,递归            array.push(arrayDeep(item));         }else {            array.push(item);        }    });    return array;}const arrays = [{a: 2}, {b: 5, child:[{c: 3}, {d: 4}]}, {f:7}, "333", 5, ['wqfe', {e:7}]];const arr = arrayDeep(arrays);arr[5][1].e = 5;console.log(arr[5][1].e); //5console.log(arrays[5][1].e); //7