js完成clone要领对种种数据类型举行复制

对种种数据类型举行复制,最初的头脑是应用typeof鉴别数据类型后应用switch语句离别赋值,但是有个题目:null、Array和Object返回的都是‘object’,所以又要细分为三种状况编写代码。个中,要推断一个对象为数组运用的是:toString.apply(obj)要领。完全代码以下:

function clone(obj){
            var copy;
            switch(typeof obj){
                case 'undefined':break;
                case 'number':
                case 'string':
                case 'boolean':copy = obj;break;
                case 'object':
                    if(obj == null) copy = null;
                    else if(toString.apply(obj) === '[object Array]')
                    {
                        copy = [];
                        for(var i in obj) copy.push(clone(obj[i]));
                    }
                    else 
                    {
                        copy = {};
                        for(var j in obj)
                            copy[j]= clone(obj[j]);
                    }
            }
            return copy;
        }
        console.log(clone(true));
        console.log(clone(12));
        console.log(clone('abc'));
        console.log(clone(null));
        console.log(clone([1,2,3]));
        console.log(clone({name:'zh',age:'18'}));
    原文作者:kvera
    原文地址: https://segmentfault.com/a/1190000007239515
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞