js/jquery 克隆对象
jQuery 中的 extend 方法:
var o = {a: [1]}; //浅拷贝 var o1 = $.extend({}, o); console.log(o1.a === o.a); // true //深拷贝 var o2 = $.extend(true, {}, o); console.log(o2.a === o.a); //false
js方法:
方法一
- 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' :
- if(obj === null){
- o = null;
- }else{
- if(obj instanceof Array){
- o = [];
- for(var i = 0, len = obj.length; i < len; 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;
- }
方法二
- function clone2(obj){
- var o, obj;
- if (obj.constructor == Object){
- o = new obj.constructor();
- }else{
- o = new obj.constructor(obj.valueOf());
- }
- for(var key in obj){
- if ( o[key] != obj[key] ){
- if ( typeof(obj[key]) == 'object' ){
- o[key] = clone2(obj[key]);
- }else{
- o[key] = obj[key];
- }
- }
- }
- o.toString = obj.toString;
- o.valueOf = obj.valueOf;
- return o;
- }
方法三
- function clone3(obj){
- function Clone(){}
- Clone.prototype = obj;
- var o = new Clone();
- for(var a in o){
- if(typeof o[a] == "object") {
- o[a] = clone3(o[a]);
- }
- }
- return o;
- }
相关推荐
88274956 2020-11-03
runner 2020-09-01
梦的天空 2020-08-25
移动开发与培训 2020-08-16
ReunionIsland 2020-08-16
lyqdanang 2020-08-16
MyNameIsXiaoLai 2020-07-08
星辰的笔记 2020-07-04
csstpeixun 2020-06-28
letheashura 2020-06-26
liaoxuewu 2020-06-26
sunzhihaofuture 2020-06-21
FEvivi 2020-06-16
坚持着执着 2020-06-16
waterv 2020-06-14
xiaoge00 2020-06-14
firejq 2020-06-14
firstboy0 2020-06-14
e度空间 2020-06-12
zhongweinan 2020-06-10