深拷贝和浅拷贝
下午面试,碰到了问深拷贝和浅拷贝有几种方式,我楞了一下,也不知道是不是没睡好午觉的原因,浅拷贝就答了使用Object.assign(),而深拷贝只想到了使用jq的extend方法。回来翻了翻笔记,才又想起一些常用的浅拷贝和深拷贝。多嘴一句,8月份的广州,在外走一下,简直都能脱水了,幸亏没中暑。
①先上菜:jq实现的extend( jQuery.extend( [deep ], target, object1 [, objectN ] ) ):
jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; };
②递归调用实现的(摘自于):
function deepCopy(p, c) { var c = c || {}; for (var i in p) { if (typeof p[i] === 'object') { c[i] = (p[i].constructor === Array) ? [] : {}; deepCopy(p[i], c[i]); } else { c[i] = p[i]; } } return c; }
③简单粗暴:
JSON.parse(JSON.stringify(obj))
JSON.parse(),JSON.stringify()兼容性问题
可以通过为IE7以及IE7以下版本的IE浏览器引入json2.js,使用json2.js来解决JSON的兼容性问题
<!--[if lt IE 7]> <script src="具体放路径/json2.js"></script> <![endif]-->
json2.js的github地址为:https://github.com/douglascrockford/JSON-js
浅拷贝:
①数组的浅拷贝:
arr.slice(0);
arr.concat();
②常用:
function extendCopy(p) { var c = {}; for (var i in p) { c[i] = p[i]; } c.uber = p; return c; } var Doctor = extendCopy(Chinese); Doctor.career = '医生'; alert(Doctor.nation); // 中国
③Object.assign()---Object.assign 方法只会拷贝源对象自身的并且可枚举的属性到目标对象身上。
Object.assign(target, ...sources)
④jq实现的extend( jQuery.extend(false, target, object1 [, objectN ] ) ):
浙公网安备 33010602011771号