0%

常用方法

hello cc

数组去重

1
2
console.log([...new Set([1, 1, 2, 2, "a", "a", "b"])]);
//[1, 2, 'a', 'b']

类型转换

1
2
3
4
5
6
7
8
let num = +"10"; // 10
let num1 = +"a"; //NaN
let bool = !!""; //false
let bool1 = !!0; //false
let bool2 = !!-1; //true
let bool3 = !![]; //true
//获取时间戳
let time = +new Date(); //Date.now()

使用===代替==

1
2
3
4
5
6
7
(([] == (0)[1]) == //true
(1)[1]) === //true
1; //false
//es6 Object.is()
NaN === NaN; //false
Object.is(1, [1]); //false
Object.is(NaN, NaN); //true

简单的随机排序

1
2
let arr = [1, 2, 3, 4, 5];
let newarr = arr.sort(() => Math.random() - 0.5); //[2, 1, 5, 3, 4]

使用 Promise 封装一个延迟器

1
2
3
4
5
6
7
8
9
10
11
function sleep(time) {
return new Promise((resolve, reject) => {
setTimeout(resolve, time);
});
}

(async () => {
console.time();
await sleep(2000);
console.timeEnd(); //这里两s后执行 //default: 2004.6728515625 ms
})();

获取文件名、文件后缀

1
2
3
4
5
6
7
8
function getFileExtName(file) {
return file.substring(file.lastIndexOf(".") + 1);
}
function getFileName(file) {
let sIndex = file.lastIndexOf("/") + 1 || 0;
let eIndex = file.lastIndexOf(".");
return file.substring(sIndex, eIndex);
}

日期格式化

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
function timeStrToDate(val, fmt = "yyyy-MM-dd") {
//时间戳转日期
let fillzero = function (n) {
return n < 10 ? "0" + n : n;
};
let isValidDate = (d) => {
return d instanceof Date && !isNaN(d.getTime());
};
let date = null;
if (isValidDate(new Date(val))) {
date = new Date(val);
} else {
let n = Number(val);
if (n == NaN) return val;
date = new Date(n);
}
let res = {
"y+": date.getFullYear(),
"M+": fillzero(date.getMonth() + 1),
"d+": fillzero(date.getDate()),
"h+": fillzero(date.getHours()),
"m+": fillzero(date.getMinutes()),
"s+": fillzero(date.getSeconds()),
};
for (let k in res) {
let reg = new RegExp(k);
if (reg.test(fmt)) {
fmt = fmt.replace(reg, res[k]);
}
}
return fmt;
}

文件转 base64

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function getBase64(file) {
return new Promise(function (resolve, reject) {
let reader = new FileReader();
let res = "";
reader.readAsDataURL(file);
reader.onload = function () {
res = reader.result;
};
reader.onerror = function (error) {
reject(error);
};
reader.onloadend = function () {
resolve(res);
};
});
}

base64 转文件

1
2
3
4
5
6
function base642file(base64, fileName) {
const b = Utils.dataURLtoBlob(base64);
b.lastModifiedDate = new Date(); // 文件最后的修改日期
b.name = fileName; // 文件名
return new File([b], fileName, { type: b.type, lastModified: Date.now() });
}

基于 qrcode 生成带 logo 的二维码

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
function generateQRCode(url, config = {}, icon, fit = "contain") {
//fit 暂未实现 用于图片的展现方式
let imgExt = ["png", "jpg", "jpeg", "bmp", "gif"];
if (imgExt.includes(Utils.getFileExtName(icon))) {
let t = Date.now();
icon = icon + `?v=${t}`;
}
let _config = {
errorCorrectionLevel: "H",
width: 300,
height: 200,
color: {
dark: "#000000",
light: "#FFFFFF",
},
...config,
};
if (_config.widh !== _config.height) {
let max = Math.max(_config.width, _config.height);
_config.width = _config.height = max;
}
let canvas = await QRCode.toCanvas(url, _config);
let ctx = canvas.getContext("2d");
let scale = 0.3;
let img = new Image();
img.setAttribute("crossOrigin", "Anonymous");
img.src = icon;
return new Promise((resolve) => {
try {
img.onload = () => {
ctx.fillStyle = "white";
let rectW = _config.width * scale;
ctx.rect(
(_config.width - rectW) / 2,
(_config.height - rectW) / 2,
_config.width * scale,
_config.height * scale
);
ctx.fill();
let max = Math.max(img.width, img.height);
const scaleFit = rectW / max;
let w = img.width * scaleFit;
let h = img.height * scaleFit;
ctx.drawImage(
img,
(_config.width - w) / 2,
(_config.height - h) / 2,
w,
h
);
resolve(canvas.toDataURL());
};
} catch (error) {
resolve(canvas.toDataURL());
}
});
}

数组分组

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
function groupBy(list, key) {
return list.reduce((rv, current) => {
(rv[current[key]] = rv[current[key]] || []).push(current);
return rv;
}, {});
}

groupBy(
[
{
name: "Tom",
gender: "1",
},
{
name: "cc",
gender: "1",
},
{
name: "lisa",
gender: "0",
},
],
"gender"
);
/*return
{
0: [
{
name: "lisa",
gender: "0",
},
],
1: [
{
name: "Tom",
gender: "1",
},
{
name: "cc",
gender: "1",
},
],
}
*/