深、浅拷贝
- 浅拷贝:
1、Object.assign(目标对象,源对象)
2、 var obj1={} for(var key in obj){ obj1[key]=obj[key] }
3、obj1={...obj};
- 深拷贝:
function cloneObject(source, target) { if (target === undefined) { if (Node.prototype.isPrototypeOf(source)) { target = document.createElement(source.nodeName); target.style = source.style.cssText; }
else if (source.constructor === Uint8Array) { target = new source.constructor(Array.from(source)); }
else if (source.constructor === Date || source.constructor === RegExp || source.constructor === Set || source .constructor === Map) { target = new source.constructor(source); }
else if (source.constructor === Function) { var arg = source.toString().match(/\((.*?)\)/)[1]; var content = source.toString().replace(/\n|\r/g, "").match(/\{(.*)\}/)[1]; target = new Function(arg, content) }
else { target = new source.constructor(); } } var names = Object.getOwnPropertyNames(source).concat(Object.getOwnPropertySymbols(source)); for (var i = 0; i < names.length; i++) { if (names[i] === "constructor") { Object.defineProperty(target, "constructor", { value: source.constructor }); continue; } var desc = Object.getOwnPropertyDescriptor(source, names[i]); if ((typeof desc.value === "object" && desc.value !== null) || typeof desc.value === "function") { var o = cloneObject(desc.value) Object.defineProperty(target, names[i], { value: o, enumerable: desc.enumerable, writable: desc.writable, configurable: desc.configurable }) }
else { Object.defineProperty(target, names[i], desc); } } return target; }
更多关于web前端培训的问题,欢迎咨询千锋教育在线名师,如果想要了解我们的师资、课程、项目实操的话可以点击咨询课程顾问,获取试听资格来试听我们的课程,在线零距离接触千锋教育大咖名师,让你轻松从入门到精通。