JS手寫面試題 --- 深拷貝
阿新 • • 發佈:2021-06-21
JS手寫面試題 --- 深拷貝(考慮到複製 Symbol 型別)
題目描述:手寫實現 深拷貝
實現程式碼如下:
function isObject(val) { return typeof val === 'object' && val !== null; } function deepClone(obj, hash = new WeakMap()) { if (!isObject(obj)) return obj; if (hash.has(obj)) { return hash.get(obj); } let target = Array.isArray(obj) ? [] : {}; hash.set(obj, target); Reflect.ownKeys(obj).forEach((item) => { if (isObject(obj[item])) { target[item] = deepClone(obj[item], hash); } else { target[item] = obj[item]; } }); return target; } var obj1 = { a: 1, b: { a: 2 } }; var obj2 = deepClone(obj1); console.log(obj2); // {a: 1, b: {…}} obj2.a = 123 console.log(obj2); // {a: 123, b: {…}} console.log(obj1); // {a: 1, b: {…}}
請忽略下面的內容!
【投稿說明】
部落格園是面向開發者的知識分享社群,不允許釋出任何推廣、廣告、政治方面的內容。
部落格園首頁(即網站首頁)只能釋出原創的、高質量的、能讓讀者從中學到東西的內容。
如果博文質量不符合首頁要求,會被工作人員移出首頁,望理解。如有疑問,請聯絡[email protected]。
【投稿說明】
部落格園是面向開發者的知識分享社群,不允許釋出任何推廣、廣告、政治方面的內容。
部落格園首頁(即網站首頁)只能釋出原創的、高質量的、能讓讀者從中學到東西的內容。
如果博文質量不符合首頁要求,會被工作人員移出首頁,望理解。如有疑問,請聯絡[email protected]。