-
Notifications
You must be signed in to change notification settings - Fork 0
/
clone.js
58 lines (53 loc) · 1.63 KB
/
clone.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
module.exports = {
/**
* 获取类型
* @param {object/array/undefined/null/number/string/...} arg 待判断类型参数
* @return {String} 参数类型(首字母大写)
*/
getType: function(arg) {
let typeStr = Object.prototype.toString.call(arg);
return typeStr.replace(/\[object|\]|\s/g, '');
},
/**
* 浅拷贝--非递归
* @param {[type]} src 待拷贝的对象
* @return {[type]} 拷贝结果
*/
shallowClone: function(src) {
if (!src && typeof src !== 'object') {
console.log('it is not a object');
}
const type = this.getType(src);
let target = type === 'Array' ? [] : {};
for (let key in src) {
if (src.hasOwnProperty(key)) {
target[key] = src[key];
}
}
return target;
},
/**
* 深拷贝--递归
* @param {[type]} src 待拷贝的对象
* @return {[type]} 拷贝结果
*/
deepClone: function(src) {
if (!src && typeof src !== 'object') {
console.log('it is not a object');
}
const type = this.getType(src);
let target = type === 'Array' ? [] : {};
for (let key in src) {
if (src.hasOwnProperty(key)) {
const subType = this.getType(src[key]);
if (subType === 'Object' || subType === 'Array') {
// Object sub
target[key] = this.deepClone(src[key]);
} else {
target[key] = src[key];
}
}
}
return target;
}
}