众所周知,对象的深浅拷贝是工作中肯定会遇到的问题。所以,今天考虑写个小的功能来记录一下
//type:boolean,true-deep,true为深拷贝, function extendCopy(type,item){ if(typeof type != "boolean" || typeof item !=‘object‘){ return } var newObj = item.constructor ==="Array" ?[]:{}; if(type){ if(window.JSON){ return JSON.parse(JSON.stringify(item)); } else{ for(prop in item){ if(getType(item[prop]) ==‘array‘ || getType(item[prop]==“object”)){ newObj[prop]= extendCopy(type,item[prop]); } else{ newObj[prop] = item[prop]; } } } } else{ for (prop in item){ newObj[prop] = item[prop]; } return newObj; } } //实现js内置类型的检测 function getType(o){ var _toString=Object.prototype.toString; var _type={ "undefined":"undefined", "number":"number", "boolean":"boolean", "string":"string", "[object Function]":"function", "[object Array]":"array", "[object RegExp]":"regexp", "[object Date]":"date", "[object Erroe]":"error" } return _type[typeof o]||_type[_toString.call(o)]||(o?"object":"null"); }
时间: 2024-11-03 21:47:21