href 链接传参转为JSON对象
function getHrefParam(href) {
if (typeof href === 'string') {
let str = href ? href.substr(href.indexOf('?') + 1) : '';
let obj = {};
str.split('&').map(ele => {
if (ele.includes('=')) {
let a = ele.split('=');
obj[a[0]] = a[1]
}
});
return obj;
} else {
return {}
}
}
时间戳转换日期格式
/**
* 时间戳转换日期格式
* @options time 时间戳或者字符串时间
* format 想要的时间格式 yyyy-MM-dd HH:mm:ss | yyyy/MM/dd HH:mm:ss
* @return 最终的字符串格式时间
* */
function formatDate (time, format = 'yyyy-MM-dd HH:mm') {
// 空值校验
if(time === null || time === undefined || time === 'NaN') {
return ''
}
let t = new Date(typeof time === 'number' ? time : String(time).replace(/-/g,'/')); // ios不兼容yyyy-MM-dd格式
let tf = function(i){return (i < 10 ? '0' : '') + i};
return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function(a) {
switch (a) {
case 'yyyy':
return tf(t.getFullYear());
case 'MM':
return tf(t.getMonth() + 1);
case 'mm':
return tf(t.getMinutes());
case 'dd':
return tf(t.getDate());
case 'HH':
return tf(t.getHours());
case 'ss':
return tf(t.getSeconds());
}
})
}
换算时间差,xx秒xx分xx小时xx天xx月xx年
//换算时间差, xx秒xx分xx小时xx天xx月xx年,与上文formatDate联合使用
function computeTimes (start, end, sort = 'reverse', formatArr = ['年', '月', '天', '小时' , '分', '秒']) {
let f1 = [...formatDate(start, 'yyyy-MM-dd').split('-'), ...formatDate(start, 'HH:mm:ss').split(':')];
let f2 = [...formatDate(end, 'yyyy-MM-dd').split('-'), ...formatDate(end, 'HH:mm:ss').split(':')];
let str = [];
f2.map((ele, i) => {
if (ele > f1[i]) {
str.push(`${(ele - f1[i])}${formatArr[i]}`)
}
});
if (sort === 'reverse') {
return str.reverse().join('')
}
return str.join('')
}
console.log('距离活动结束:',computeTimes(Date.now(), '2022-08-19 16:56:56'));
console.log('剩余时间:',computeTimes(Date.now(), '2022-08-19 16:56:56', ''));
console.log('距离活动开始:',computeTimes('2022-01-01', Date.now()));
计算一个月,如【2023-02-01,2023-02-28】
function computedMonthTime(time) {
let year = new Date(time || Date.now()).getFullYear();
let month = new Date(time || Date.now()).getMonth() + 1;
let endDate = new Date(new Date(`${month < 12 ? year : year + 1}/${month < 12 ? `${month < 10 ? '0': ''}${ month + 1 }` : '01'}`).getTime() - 3600 * 1000 * 24).getDate();
month < 10 && (month = `0${month}`);
return [`${year}-${month}-01`, `${year}-${month}-${endDate}`];
}
手机号格式
/^1(3|4|5|6|7|8|9)\d{9}$/.test(String(mobile))
替换手机号码中间四位
String(number).replace(/^(\d{3})\d{6}(\d{2})$/, "$1******$2")
正则:验证>0且保留2位小数(排除0.0,0.00)
/^([1-9]\d*(\.\d{1,2})?|([0](\.([0][1-9]|[1-9]\d?))))$/.test(String(number));
小数点运算精度丢失
原因:计算机是2进位存储;
解决方案:
例如:计算a+b 的值
let a = 0.1;
let b = 0.2;
let maxLength = Math.max(String(a).split('.')[1].length, String(b).split('.')[1].length);
let p = Math.pow(10, maxLength);
let m = (a*p + b*p)/p;