- 淺拷貝:
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前端培訓的問題,歡迎咨詢千鋒教育在線名師,如果想要了解我們的師資、課程、項目實操的話可以點擊咨詢課程顧問,獲取試聽資格來試聽我們的課程,在線零距離接觸千鋒教育大咖名師,讓你輕松從入門到精通。