美文网首页
js 深拷贝方法

js 深拷贝方法

作者: 彬彬彬boboc | 来源:发表于2018-04-25 15:29 被阅读0次

function clone(obj) {

    var o;

    switch (typeof obj) {

        case "undefined":

            break;

        case "string":

            o = obj + "";

            break;

        case "number":

            o = obj - 0;

            break;

        case "boolean":

            o = obj;

            break;

        case "object": // object 分为两种情况 对象(Object)或数组(Array)

            if (obj === null) {

                o = null;

            } else {

                if (obj.constructor === "Array") {

                    o = [];

                    for (var i = 0; i < obj.length; i++) {

                        o.push(clone(obj[i]));

                    }

                } else {

                    o = {};

                    for (var k in obj) {

                        o[k] = clone(obj[k]);

                    }

                }

            }

            break;

        default:

            o = obj;

            break;

    }

    return o;

}

let aaa=[];

let bbb = [{name:'小明', age:'大明', num:[1,2,3,5,4,]},{name:'250小明', age:'85明', num:[1,2,3,5,4,]}]

aaa=clone(bbb);

console.log(aaa);

相关文章

网友评论

      本文标题:js 深拷贝方法

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