js数组的深拷贝

数组中的slice() & concat() 均为浅拷贝方法

// 深层递归 
    var array = [
        { name: 1 },
        { name: 2, age: { age: "1qwe" } },
        { name: 3 }
    ];
    function copy(obj) {
        var newArr = obj.constructor === Array ? [] : {};
        if (typeof obj !== 'object') {
            return;
        }
        for (var i in obj) {
            newArr[i] = typeof obj[i] === 'object' ? copy(obj[i]) : obj[i];
        }
        return newArr
    }
    var new_arr = copy(array)
    new_arr[0].name = 111;
    new_arr[1].age.age = 2211112;
    console.log(array);
    console.log(new_arr);

你可能感兴趣的:(JavaScript,javascript,前端,vue.js)