- 淺拷貝:
1、Object.assign(目標(biāo)對(duì)象,源對(duì)象)
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; }
更多關(guān)于web前端培訓(xùn)的問(wèn)題,歡迎咨詢千鋒教育在線名師,如果想要了解我們的師資、課程、項(xiàng)目實(shí)操的話可以點(diǎn)擊咨詢課程顧問(wèn),獲取試聽資格來(lái)試聽我們的課程,在線零距離接觸千鋒教育大咖名師,讓你輕松從入門到精通。