对各种数据类型进行复制,最初的思想是利用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'}));