diff --git a/README.md b/README.md index 3bc019c..d4b307c 100644 --- a/README.md +++ b/README.md @@ -1172,7 +1172,7 @@ var newObject = deepClone(obj); ```javascript function deepClone(object){ - var newObject = {}; + var newObject = Array.isArray(object) ? [] : {}; for(var key in object){ if(typeof object[key] === 'object' && object[key] !== null ){ newObject[key] = deepClone(object[key]); @@ -1201,6 +1201,8 @@ var personalDetail = { ``` So when we do deep clone then we should copy every property (including the nested object). +Without `Array.isArray()` check, `[1, 2, 3]` was silently cloned as `{ "0": 1, "1": 2, "2": 3 }` since both arrays and objects return `"object"` for `typeof`,fixed by initializing `newObject` as `[]` when the input is an array + ## Question 30. Best way to detect `undefined` object property in JavaScript.