核心步骤
- 如果对象参数的数据类型不为"object"或为"null",则直接返回该参数。
- 如果是"object",就获取该参数的构造函数名,通过正则表达式判断该对象是否为函数、正则、日期、ES6新对象等,如果返回true,则直接返回该参数。
- 当以上条件判断之后函数依然没有结束时,此时通过数组的原型方法判断该参数为普通对象或数组并创建相应数据类型的新变量。
- 进入遍历体,将对象参数的每一项赋值给新变量。
- 最终返回该新变量。
const _shallowClone = target => {
if(typeof target === 'object' && target !== null) {
const constructor = target.constructor
if(/^(Function|RegExp|Date|Map|Set)$/i.test(constructor.name)) return target
const cloneTarget = Array.isArray(target) ? [] : {}
for(prop in target) {
if(target.hasOwnProperty(prop)) {
cloneTarget[prop] = target[prop]
}
}
return cloneTarget
} else {
return target
}
}