Skip to content

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

Open
@wuxianqiang

Description

@wuxianqiang

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

循环

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) //李四

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @wuxianqiang

        Issue actions

          怎样拷贝数组(深/浅拷贝) · Issue #29 · wuxianqiang/blog