0%

常用的JS方法

常用的JS方法

1、base64转二进制(Blob)数据

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function b64toBlob(b64Data, contentType = '', sliceSize = 512) {
const byteCharacters = atob(b64Data);
const byteArrays = [];

for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);

const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}

const byteArray = new Uint8Array(byteNumbers);

byteArrays.push(byteArray);
}

const blob = new Blob(byteArrays, { type: contentType });
return blob;
}

方法二

1
2
3
4
5
6
7
8
9
10
11
function base64toBlob(b64Data, contentType = '') {
const byteCharacters = atob(b64Data);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);

const blob = new Blob([byteArray], { type: contentType });
return blob;
}

2、格式化参数对象

1
2
3
4
5
6
7
function jsonForm(obj) {
let result = '';
Object.keys(obj).forEach((key, index) => {
result += `${index === 0 ? '' : '&'}${key}=${encodeURIComponent(obj[key])}`;
});
return result;
}

3、判断值是否在区间内

1
2
3
4
5
6
7
function valueBettween({
min = required('最小值min'),
max = required('最大值max'),
value = required('输入值value'),
}) {
return Math.min(Math.max(min, value), max);
}

4、格式化Date

① 格式时间

  • 如为今天,则格式为:上/下午 时:分;
  • 如为昨天,则格式为:昨天 时:分;
  • 其余时间格式为:年-月-日 时:分。
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
formatDateForMsg(date) {
const curDate = new Date();
// + 1000 处理零点零零问题
const oneDayS = 86400000;
const resH = Help.formatD(date.getHours());
const resM = Help.formatD(date.getMinutes());
const resHM = `${resH}:${resM}`;
const DayS = date.getTime() + 1000;
const todayS = ((curDate.getHours() * 60 + curDate.getMinutes()) * 60 + curDate.getSeconds()) * 1000;
const lastDayS = curDate.getTime() - todayS;
const differS = DayS - lastDayS;
if (differS >= 0) {
if (resH < 12) {
return `上午 ${resHM}`;
}
return `下午 ${resHM}`;
}
if (differS + oneDayS < 0) {
const y = date.getFullYear();
const m = Help.formatD(date.getMonth() + 1);
const d = Help.formatD(date.getDate());
return `${y}-${m}-${d} ${resHM}`;
}
return `昨天 ${resHM}`;
}

② 格式化小于10的数字——‘09’

1
2
3
4
5
6
formatD(num) {
if (num < 0) {
return num;
}
return num < 10 ? `0${num}` : num;
}