美文网首页让前端飞技术干货
怎样拷贝数组(深/浅拷贝)

怎样拷贝数组(深/浅拷贝)

作者: 前端精髓 | 来源:发表于2018-01-07 22:04 被阅读52次

    拷贝数组就是把原来数组的每一项保存在一个新数组中,这样在操作数组的同时,另一个数组就不会受影响,因为数组是引用类型的值,所以在拷贝数组的同时并不能直接复制变量值,我们有一下几种方法可以使用。

    循环

    var ary1 = [1,2,3];
    
    for (var i = 0, ary2 = Array(ary1.length); i < ary1.length; i++) ary2[i] = ary1[i];
    

    slice

    var ary1 = [1,2,3];
    
    var ary2 = ary1.slice();
    

    运算符

    var ary1 = [1,2,3];
    
    var ary2 = [...ary1];
    

    from

    var ary1 = [1,2,3];
    
    var ary2 = Array.from(ary1);
    

    concat

    var ary1 = [1,2,3];
    
    var ary2 = [].concat(ary1);
    

    说到深拷贝,比较特殊的就是数组和对象了,所以在编写方法的时候要分别做不同的处理,代码如下:

    
    let ary = [1,[2, {name: "张三"}]];
    
    function copyAry(options) {
        return copy(options)
    }
    
    function copy(ary) {
        let newAry = []
        for (const item of ary) {
            let value = item;
            if (Object.prototype.toString.call(value) === "[object Object]") value = copyObj(value);
            if (Object.prototype.toString.call(value) === "[object Array]") value = copyAry(value);
            newAry.push(value);
        }
        return newAry;
    }
    
    function copyObj(obj) {
        let newObj = {};
        for (const key in obj) {
            let value = obj[key];
            if (Object.prototype.toString.call(value) === "[object Object]") value = copyObj(value);
            if (Object.prototype.toString.call(value) === "[object Array]") value = copyAry(value);
            newObj[key] = value;
        }
        return newObj;
    }
    
    // 测试
    let newAry = copyAry(ary);
    ary[1][1].name="李四"
    console.log(newAry[1][1].name) //张三
    console.log(ary[1][1].name) //李四
    

    查看作者源码

    相关文章

      网友评论

        本文标题:怎样拷贝数组(深/浅拷贝)

        本文链接:https://www.haomeiwen.com/subject/cmomnxtx.html