题目:
- 参数对象和参数对象的每个数据项的数据类型范围仅在数组、普通对象({})、基本数据类型中]
- 无需考虑循环引用问题
划重点:题目中数据只有: 基本数据类型,普通对象,数组,且不会出现循环引用问题。
思路
考虑到对象的层级嵌套,因此很容易想到使用**递归的思路**来解决该题目中的嵌套问题
递归的代码框架
const clone = target => {
// 什么是base case?
// 递归解决的是什么问题?clone recursely
}
题目的全部参考代码
const _sampleDeepClone = target => {
// base case
if (target == null || typeof target !== 'object') {
return target;
}
const cloneTarget = Array.isArray(target) ? [] : {};
for (let key in target) {
if (target.hasOwnProperty(key)) {
if (target[key] && typeof target[key] == 'object') {
// 递归
cloneTarget[key] = _sampleDeepClone(target[key]);
} else {
// 基本数据类型
cloneTarget[key] = target[key];
}
}
}
return cloneTarget;
};