index.js
1.43 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
export function debounce(fn, delay, triggerNow) {
var t = null;
var debounced = function(){
var _self = this,
args = arguments;
if(t){
clearTimeout(t);
}
if(triggerNow){
var exec = !t;
t = setTimeout(function(){
t = null;
}, delay);
if(exec){
// 初次进来
fn.apply(_self, args);
}
}else{
t = setTimeout(function(){
fn.apply(_self, args);
}, delay);
}
}
debounced.remove = function(){
clearTimeout(t);
t = null;
}
return debounced;
}
//正则表示式是干什么的? 字符串匹配利器(难,规则多)
export function formatDate(date, fmt) {
//1.获取年份
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
}
//2.获取
//M+ ->正则表达式一个规则
//
let o = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds()
};
for (let k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
let str = o[k] + '';
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
}
}
return fmt;
};
//填补左边的零(一般返回字符串最后两位)
function padLeftZero (str) {
return ('00' + str).substr(str.length);
};