-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path手写代码.html
105 lines (83 loc) · 2.94 KB
/
手写代码.html
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id='root' style="width: 300px;height: 300px;border: 1px solid red;">
</div>
<script>
let root = document.querySelector('#root')
root.addEventListener('mousedown', function () {
console.log(1, this);
})
root.addEventListener('mousemove', debounce(function (e) { console.log(2, e, this); }, 300, true))
// 防抖
function debounce(func, wait, immediate) {
var timeout, result;
function debounced() {
var context = this;
var args = arguments;
if (timeout) clearTimeout(timeout);
if (immediate) {
// 如果已经执行过,不再执行
var callNow = !timeout;
timeout = setTimeout(function () {
timeout = null;
}, wait)
if (callNow) result = func.apply(context, args)
}
else {
timeout = setTimeout(function () {
func.apply(context, args)
}, wait);
}
return result
}
debounced.cancel = function () {
if (timeout) clearTimeout(timeout);
timeout = null
}
return debounced
}
</script>
<script>
// 手写trim
String.prototype.myTrim = function () {
return this.replace(/^\s+|\s+$/g, '')
}
Array.prototype.flat = function () {
let isArray = array => Object.prototype.toString.call(array) === '[object Array]'
let result = []
if (isArray(this)) {
this.forEach(item => {
// if (!isArray(item)) {
// result.push(item)
// } else {
// result = result.concat(item.flat())
// }
result = result.concat(isArray(item) ? item.flat() : item)
});
}
return result
}
Array.prototype.flatReduce = function () {
console.log(77, [1, 2].concat([1]));
let isArray = array => Object.prototype.toString.call(array) === '[object Array]'
return this.reduce((a, item) => {
// console.log(a);
if (isArray(item)) {
return a.concat(item.flatReduce())
} else {
a.push(item)
return a
}
}, [])
}
console.log([1, , , 2, 3, [2, 3, 4], [234, [235, { name: '张三' }]]].flatReduce());
</script>
</body>
</html>