工作中常用代码片段

  目录

工作中常用代码片段

记录些工作中常用到的代码片段,便于CV使用,提高效率

根据日期对象获取格式化日期字符串

1
2
3
4
5
6
7
const getYrarMonthDay = date=> {
let year = date.getFullYear();
let month = date.getMonth() + 1;
month = month>9?month:'0'+month;
let day = date.getDate();
return year + '-' + month + '-' + day;
}

解析url中的参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const urlQuery2Object = url=> {
url = !url ? window.location.href : url;
if(url.indexOf('?') === -1) {
return {};
}
var search = url[0] === '?' ? url.substr(1) : url.substring(url.lastIndexOf('?') + 1);
if (search === '') {
return {};
}
search = search.split('&');
var query = {};
for (var i = 0; i < search.length; i++) {
var pair = search[i].split('=');
query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
}
return query;
}

触发input的选择获取文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const triggerInputFile = function(callBack) {
return new Promise((resolve, reject)=> {
try {
let nInput = document.createElement('input');
nInput.setAttribute('type', 'file');
nInput.setAttribute('accept', 'image/png,image/jpg,image/jpeg');
document.body.appendChild(nInput);
nInput.addEventListener('change', (ev)=> {
if(ev.target.files[0].size > 1024*1024*2) {
alert('图片大小不得超过2M');
return void 0;
}
resolve(ev);
document.body.removeChild(nInput);
}, false);
nInput.click();
}catch(err) {
reject(err);
}
});
}

获取宿主浏览器环境

详细内容可异步这里

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
const getPlatformOs = ()=> {
return new Promise((resolve, reject)=> {
try {
var u = navigator.userAgent;
var ua = navigator.userAgent.toLowerCase();
// 判断是否在微信内置浏览器打开
if(ua.match(/MicroMessenger/i) == "micromessenger") {
resolve('weixin')
return void 0;
}
// 判断安卓
if(u.indexOf("Android") > -1 || u.indexOf("Linux") > -1) {
resolve('android')
return void 0;
}
// 判断iOS
if(!!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
resolve('ios');
return void 0;
}
}catch(err) {
reject(err);
}
});
}

判断宿主环境是否是微信小程序

详细内容可异步这里

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const isWeiApp = ()=> {
return new Promise(function(resolve, reject) {
try{
var ua = navigator.userAgent.toLowerCase();
if(ua.match(/MicroMessenger/i)=="micromessenger") {
wx.miniProgram.getEnv((res)=>{
if (res.miniprogram) {
resolve(true);
}else {
resolve(false);
}
})
}else{
resolve(false);
}
}catch(err) {
reject(err);
}
});
}

复制内容到剪贴板

1
2
3
4
5
6
7
8
9
10
11
12
13
function copyToBoard(value) {
const element = document.createElement('textarea')
document.body.appendChild(element)
element.value = value
element.select()
if (document.execCommand('copy')) {
document.execCommand('copy')
document.body.removeChild(element)
return true
}
document.body.removeChild(element)
return false
}

对象转化为FormData对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function getFormData(object) {
const formData = new FormData()
Object.keys(object).forEach(key => {
const value = object[key]
if (Array.isArray(value)) {
value.forEach((subValue, i) =>
formData.append(key + `[${i}]`, subValue)
)
} else {
formData.append(key, object[key])
}
})
return formData
}

睡眠sleep

方法1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
sleep(time) {
return new Promise((resolve, reject)=> {
setTimeout(()=> {
resolve();
}, time);
});
}

// demo 发送验证码
async onSendCode() {
let num = 60;
while(num>0) {
num--;
this.form.codeBtnStr = num;
await sleep(1000);
}
this.form.codeBtnStr = '发送验证码';
}

方法2

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
const sleep = (timeOut, oneCb)=> {
return new Promise((resolve, reject)=> {
const innerSleep = (timeOut, oneCb)=> {
oneCb(timeOut);
setTimeout(()=> {
if(timeOut<=1) {
resolve();
return ;
}
timeOut-=1;
oneCb(timeOut);
innerSleep(timeOut, oneCb);
}, 1000);
}
innerSleep(timeOut, oneCb);
});
}
// demo 发送验证码
onSendCode() {
sleep(60, (val)=> {
this.form.codeBtnStr = val;
}).then(()=> {
this.form.codeBtnStr = '发送验证码';
});
},

倒计时 时分秒

未支付订单的倒计时效果中会使用到

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 countDown(originDate, rangeMinute) { 
// originDate 倒计时的起始时间,如2023-12-12 8:09:15
// rangeMinute 倒计时范围,1个小时倒计时还是30分钟倒计时
// requestAnimationFrame兼容性处理
var requestAnimationFrame =window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame || window.oRequestAnimationFrame || function (cb) { window.setTimeout(cb, 1000 / 60) };

var preTime = Date.now(); // 计算1秒前置时间
var countTime = Date.now(); // 倒计时的时间
var innerFn = function(callback) {
requestAnimationFrame(function() {
var laterTime = Date.now(); // 计算1秒的后置时间
innerFn.timer&&innerFn(callback); // 当timer为false时,不执行递归循环
if((laterTime-preTime>=1000)) { // 每隔1秒钟触发
countTime += 1000; // 倒计时时间减1秒
preTime = laterTime; // 计算1秒前置时间更改
var originDateTime = new Date(originDate).getTime(); // 倒计时的原始时间
if(laterTime - originDateTime > rangeMinute*1000) {
console.error('倒计时时间超出范围');
innerFn.timer = false;
return void 0;
}
var str = format(originDateTime, countTime); // 格式化成hh:mm:ss
callback(str); // 执行回调, rangeMinute
}
});
}
innerFn.timer = true; // 是否执行递归的flag
// 结束倒计时函数
innerFn.clear= function() {
innerFn.timer = false;
}
// 工具函数,时间戳转成hh:mm:ss格式
// 将时间戳格式化最主要的思路是%操作
function format(originDateTime, currentDateTime) {
var time = rangeMinute - (currentDateTime - originDateTime)/1000;
if(time<=0) innerFn.timer = false;
var hh = parseInt(time/3600);
var mm = parseInt(time%3600/60);
var ss = parseInt(time%3600%60);
hh = hh<10?('0'+hh):hh;
mm = mm<10?('0'+mm):mm;
ss = ss<10?('0'+ss):ss;
return hh + ':' + mm + ':' + ss;
}
return innerFn;
}

// 使用
var showCoutn = countDown('2023-12-20 8:09:08', 1800);
showCoutn((val)=> {
console.log(val);
});

// 10秒后倒计时结束
setTimeout(()=> {
showCoutn.clear();
}, 10000);

下载文件

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
// 方法1:
// fileBlob必须是Blob格式文件,axios请求中设置responseType: 'blob'
// fileName文件名
downloadFile(fileBlob, fileName) {
let reader = new FileReader();
reader.readAsDataURL(fileBlob);
reader.onload = evt=> {
let body = document.body;
let a = document.createElement('a');
a.download = fileName;
a.href = evt.target.result;
body.append(a);
a.click();
body.removeChild(a);
}
}
// 方法2:
downloadFile(fileBlob, fileName) {
let url = window.URL.createObjectURL(fileBlob);
let body = document.body;
let a = document.createElement('a');
a.download = fileName;
a.href = url;
body.append(a);
a.click();
body.removeChild(a);
window.URL.revokeObjectURL(url); //释放掉blob对象
}

retry

当接口请求失败后,每间隔几秒,再重发几次

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* 
* @param {function} fn - 方法名
* @param {number} delay - 延迟的时间
* @param {number} times - 重发的次数
*/
function retry(fn, delay, times) {
return new Promise((resolve, reject) => {
function func() {
Promise.resolve(fn()).then(res => {
resolve(res);
})
.catch(err => {
// 接口失败后,判断剩余次数不为0时,继续重发
if (times !== 0) {
setTimeout(func, delay);
times--;
} else {
reject(err);
}
});
}
func();
});
}

控制请求最大并发数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*
* 控制并发数
* @param {array} list - 请求列表
* @param {number} num - 最大并发数
*/
function control(list, num) {
function fn() {
if (!list.length) return;
// 从任务数 和 num 中 取最小值,兼容并发数num > list.length的情况
let max = Math.min(list.length, num);
for (let i = 0; i < max; i++) {
let f = list.shift();
num--;
// 请求完成后,num++
f.finally(() => {
num++;
fn();
});
}
}
fn();
}

根据value取出label

使用场景,在table表格中,数据只有下拉选项的value,需要获取label

1
2
3
4
5
6
7
8
9
function value2label(list, value) {
var obj = list.filter(item=> {
return +item.value === +value;
})[0] || {};
return obj.label;
}
// 使用
var list = [{ label: '沈阳', value: 1}, { label: '大连', value: 2} ];
value2label(list, 1); // '沈阳'

获取元素样式

1
2
3
4
const getStyle = function(el, name) {
let style = el.currentStyle ? el.currentStyle:document.defaultView.getComputedStyle(el, null);
return style[name];
}

彩色log

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
/**
* Print colored text with `console.log`.
*
* Usage:
* colorLog('fgCyan')('some text'); // cyan text.
*/
function colorLog() {
var COLOR_RESET = '\x1b[0m';
var COLOR_MAP = {
bright: '\x1b[1m',
dim: '\x1b[2m',
underscore: '\x1b[4m',
blink: '\x1b[5m',
reverse: '\x1b[7m',
hidden: '\x1b[8m',

fgBlack: '\x1b[30m',
fgRed: '\x1b[31m',
fgGreen: '\x1b[32m',
fgYellow: '\x1b[33m',
fgBlue: '\x1b[34m',
fgMagenta: '\x1b[35m',
fgCyan: '\x1b[36m',
fgWhite: '\x1b[37m',

bgBlack: '\x1b[40m',
bgRed: '\x1b[41m',
bgGreen: '\x1b[42m',
bgYellow: '\x1b[43m',
bgBlue: '\x1b[44m',
bgMagenta: '\x1b[45m',
bgCyan: '\x1b[46m',
bgWhite: '\x1b[47m'
};
let prefix = [];
for (let i = 0; i < arguments.length; i++) {
let color = COLOR_MAP[arguments[i]];
color && prefix.push(color);
}
prefix = prefix.join('');
return function (text) {
console.log(prefix + text + COLOR_RESET);
};
};
colorLog('bgCyan', 'fgWhite')('some text');