utils.js
2.46 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
/*
* @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-04-08 17:16:46
* @LastEditors: 前端 qianduan01@didihu.com.cn
* @LastEditTime: 2024-04-16 10:13:29
* @FilePath: \gl_tape\utils\utils.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
function convertDateTimeFormat(dateTimeStr, separator = "-") {
const date = new Date(dateTimeStr);
const year = date.getFullYear();
const month = ("0" + (date.getMonth() + 1)).slice(-2); // 月份是从0开始的
const day = ("0" + date.getDate()).slice(-2);
const hours = ("0" + date.getHours()).slice(-2);
const minutes = ("0" + date.getMinutes()).slice(-2);
const seconds = ("0" + date.getSeconds()).slice(-2);
return `${year}${separator}${month}${separator}${day} ${hours}:${minutes}:${seconds}`;
}
function deepClone(value) {
// 排除原始类型的情况,函数时也满足此条件
if (typeof value !== "object" || value === null) {
return value;
}
// 克隆结果:1.数组 2.普通对象
const result = Array.isArray(value) ? [] : {};
// 设置克隆结果的原型链为 value 的原型链(即保持原型一致)
Object.setPrototypeOf(result, Object.getPrototypeOf(value));
// 浅层克隆
for (const key in value) {
// 排除原型上的属性
if (value.hasOwnProperty(key)) {
result[key] = deepClone(value[key]); // 针对这个对象的每一个属性值进行克隆,则达到深度克隆效果
}
}
return result;
}
//精确除法
function accDiv(arg1, arg2) {
var t1 = 0,
t2 = 0,
r1,
r2;
try {
t1 = arg1.toString().split(".")[1].length;
} catch (e) {}
try {
t2 = arg2.toString().split(".")[1].length;
} catch (e) {}
r1 = Number(arg1.toString().replace(".", ""));
r2 = Number(arg2.toString().replace(".", ""));
return (r1 / r2) * Math.pow(10, t2 - t1);
}
function debounce(fn, timer) {
var t = null;
return function () {
if (t) {
clearTimeout(t);
}
if (t == null) {
fn.apply(this, arguments);
}
t = setTimeout(() => {
t = null;
}, timer);
};
}
var throttle = function (fn, delay) {
var timer = null;
return function () {
var context = this,
args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
};
export default {
convertDateTimeFormat,
deepClone,
accDiv,
debounce,
throttle,
};