题目
请补全JavaScript代码,要求实现对象参数的深拷贝并返回拷贝之后的新对象。
注意:
1. 参数对象和参数对象的每个数据项的数据类型范围仅在数组、普通对象({})、基本数据类型中]
2. 无需考虑循环引用问题
编辑
核心代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>浅拷贝</title> </head> <body> <!-- 如果对象参数的数据类型不为"object"或为"null",则直接返回该参数 如果是"object",就获取该参数的构造函数名,通过正则表达式判断该对象是否为函数、正则、日期、ES6新对象等,如果返回true,则直接返回该参数 当以上条件判断之后函数依然没有结束时,此时通过数组的原型方法判断该参数为普通对象或数组并创建相应数据类型的新变量 进入遍历体,将对象参数的每一项赋值给新变量 最终返回该新变量 --> <script type="text/javascript"> 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 } } </script> </body> </html>
