-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclone.js
More file actions
91 lines (74 loc) · 2.09 KB
/
Copy pathclone.js
File metadata and controls
91 lines (74 loc) · 2.09 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// 数组复制
/**
* 浅拷贝
* @param arr
*/
function clone(arr) {
return arr.concat();
// 或者使用slice
// return arr.slice();
// 支持类数组对象
// return Array.prototype.slice.call(arr);
}
/**
* 简易深拷贝
* 不支持function
* 不支持低版本浏览器
* @param arr
*/
function deepClone(arr) {
return JSON.parse(JSON.stringify(arr));
}
function extend(deep, target, source) {
for (var i in source) {
if (deep) {
} else {
if (source.hasOwnProperty(i)) { // 不要把原型上的属性拷贝过来
target[i] = source[i];
}
}
}
}
// 上面的方法并没有考虑到ES5属性描述的情况,也就是说如果有getter setter或对象被freeze了,这些特性是拷贝不过来的
function extend1(deep, target, source) {
function isDescUse (obj) {
return !obj.writable || !obj.enumerable || !obj.configurable || obj.get || obj.set;
}
for (var i in source) {
if (deep) {
// 这里就是递归了
// 要注意先判断Array,然后Object,基本类型和function直接拷贝
} else {
if (source.hasOwnProperty(i)) { // 不要把原型上的属性拷贝过来
var description = Object.getOwnPropertyDescriptor(source, i);
if (description && isDescUse()) {
Object.defineProperty(target, i, description);
} else {
target[i] = source[i];
}
}
}
}
}
var arr = arrayGenerator(10000);
function arrayGenerator(length) {
var arr = [];
// var unit = Math.pow(10,(''+length).length-1);
var unit = length;
while (length--) {
arr.push(Math.floor(Math.random() * unit));
}
return arr;
}
function cloneTesting(arr) {
console.time('concat:');
arr.concat();
console.timeEnd('concat:');
console.time('slice:');
arr.slice();
console.timeEnd('slice:');
console.time('concat1:');
[].concat(arr);
console.timeEnd('concat1:');
}
cloneTesting(arr);