1.评论数,销量等数字的格式化
export function handleNum(num) {
if (num < 1000) {
return num
}
if (num < 10000 && num >= 1000) {
let numArr = ((num / 1000) + '').split('.')
if (numArr.length > 1) {
if (numArr[1][0] === '0') {
return numArr[0] + '000+'
} else {
return numArr[0] + numArr[1][0] + '00+'
}
} else {
return (numArr[0] + '000+')
}
} else if (num >= 10000) {
let numArr = ((num / 10000) + '').split('.')
if (numArr.length > 1) {
if (numArr[1][0] === '0') {
return numArr[0] + '万+'
} else {
return numArr[0] + '.' + numArr[1][0] + '万+'
}
} else {
return (numArr[0] + '万+')
}
}
}
2.解决ios端时间不适配,NAN问题
data:时间
fmt:类型,例如:yyyy/MM/dd 或者 yyyy-MM-dd
formatDateIos: function(date, fmt) {
if (date == null || date == '' || date == undefined)
return null;
try {
//解决ios手机时间格式化NAN问题
if (typeof(date) == "string" && date.indexOf('-') != -1) {
date = date.replace(/-/g, '/');
}
date = new Date(date);
} catch (e) {
date = date;
}
fmt = fmt ? fmt : 'yyyy-MM-dd';
var o = {
"M+": date.getMonth() + 1, //月份
"d+": date.getDate(), //日
"H+": date.getHours(), //小时
"m+": date.getMinutes(), //分
"s+": date.getSeconds(), //秒
"q+": Math.floor((date.getMonth() + 3) / 3), //季度
"S": date.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1
.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[
k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
},
3.生成随机数/随机色
randomNum: function(n) {
let sString = "";
let strings = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
for (i = 0; i < n; i++) {
ind = Math.floor(Math.random() * strings.length);
sString += strings.charAt(ind);
}
return sString
},
// 生成随机色
getRandomColor: function() {
let color = `#${Math.floor(Math.random() * 0xffffff).toString(16)}`
return color
},
4.校验方法
isNullOrEmpty: function(value) {
//是否为空
return (value === null || value === '' || value === undefined) ? true : false;
},
trim: function(value) {
//去空格
return value.replace(/(^\s*)|(\s*$)/g, "");
},
isMobile: function(value) {
//是否为手机号
return /^(?:13\d|14\d|15\d|16\d|17\d|18\d|19\d)\d{5}(\d{3}|\*{3})$/.test(value);
},
isqqEmail: function(value) {
//是否为qq邮箱
return /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value);
},
checkLoginPwd: function(value) {
//密码为8~20位数字和字母组合
return /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/.test(value);
},
checkPayPwd: function(value) {
//校验密码为6位数字
if (value.length == 6 && /^[0-9]*$/.test(Number(value))) {
return true;
}
},
formatNum: function(num) {
//格式化手机号码
if (utils.isMobile(num)) {
num = num.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
}
return num;
},
rmoney: function(money) {
//金额格式化
return parseFloat(money).toFixed(2).toString().split('').reverse().join('').replace(/(\d{3})/g, '$1,')
.replace(
/\,$/, '').split('').reverse().join('');
},
encryptionMobile: function(mobile) {
//隐藏手机号中间4位
mobile = "" + mobile;
var reg = /(\d{3})\d{4}(\d{4})/;
var tel1 = mobile.replace(reg, "$1****$2")
return tel1;
},
isUserName: function(name) {
//校验用户名规则
var reg = /^[a-zA-Z_\u4E00-\u9FA50-9]{2,15}$/
return reg.test(name)
},
isPassword: function(password) {
//校验密码规则
var reg = /^[a-zA-Z_0-9.]{6,15}$/
return reg.test(password)
},
5.时间的格式化
//获取当前时间并格式化
getCurrentDate: function() {
var dateTime = new Date();
var year = dateTime.getFullYear();
var month = dateTime.getMonth() + 1;
var day = dateTime.getDate();
return year + '-' + month + '-' + day
},
//根据需求获取时间
formatFullTime: function(timestamp, n = 1) {
if (String(timestamp).length === 10) {
timestamp *= 1000
}
let date = new Date(timestamp)
let year = date.getFullYear()
let month = date.getMonth() + 1
let day = date.getDate()
let hour = ''
if(date.getHours() < 10){
hour = '0' + date.getHours()
}else {
hour = date.getHours()
}
let minute = ''
if(date.getMinutes() < 10){
minute = '0' + date.getMinutes()
}else {
minute = date.getMinutes()
}
let second = date.getSeconds()
if (n === 1) return `${year}-${month}-${day} ${hour}:${minute}:${second}`
if (n === 2) return `${month}-${day}`
if (n === 3) return `${year}/${month}/${day}`
if (n === 4) return `${year}-${month}-${day}`
if (n === 5) return `${year}/${month}/${day} ${hour}:${minute}:00`
},
//获取多少天后的日期
getDay: function(num, str) { //获取num后的日期,-1为昨天,1为明天,str为日期间的分隔符一般为'/'或者'-'
var today = new Date();
var nowTime = today.getTime();
var ms = 24 * 3600 * 1000 * num;
today.setTime(parseInt(nowTime + ms));
var oYear = today.getFullYear();
var oMoth = (today.getMonth() + 1).toString();
if (oMoth.length <= 1) oMoth = '0' + oMoth;
var oDay = today.getDate().toString();
if (oDay.length <= 1) oDay = '0' + oDay;
return oYear + str + oMoth + str + oDay;
},
// 判断日期是否是今天
isToday: function(date) {
return date.toISOString().slice(0, 10) === new Date().toISOString().slice(0, 10)
},
// 秒数转换为 hh:mm:ss 格式
formatSeconds(s) {
return new Date(s * 1000).toISOString().substr(11, 8)
},
// 设置起始时间和结束时间,然后计算出每间隔一定时间后的时间数组
startTime1:开始时间的时
startTime2:开始时间的分
endTime1:结束时间的时
endTime2:结束时间的分
timeslot(startTime1, startTime2, endTime1, endTime2, step) { // step = 间隔的分钟
let date = new Date()
// 时分秒设置从零点开始
date.setHours(startTime1)
date.setUTCMinutes(startTime2)
console.log(date)
let arr = [],
timeArr = [];
let slotNum = 24 * 60 / step // 算出多少个间隔
for (var f = 0; f < slotNum; f++) { // stepM * f = 24H*60M
let time = new Date(Number(date.getTime()) + Number(step * 60 * 1000 * f))
let hour = ''
let sec = ''
time.getHours() < 10 ? hour = '0' + time.getHours() : hour = time.getHours() // 获取小时
time.getMinutes() < 10 ? sec = '0' + time.getMinutes() : sec = time.getMinutes() // 获取分钟
// console.log('slot',hour,sec,endTime1,endTime2);
timeArr.push(hour + ':' + sec)
}
return timeArr
},
6.金额中文化
NoToChinese(num) {
if (!/^\d*(\.\d*)?$/.test(num)) {
alert("Number is wrong!");
return "Number is wrong!";
}
var AA = new Array("零", "一", "二", "三", "四", "五", "六", "七", "八", "九");
var BB = new Array("", "十", "百", "千", "万", "亿", "点", "");
var a = ("" + num).replace(/(^0*)/g, "").split("."),
k = 0,
re = "";
for (var i = a[0].length - 1; i >= 0; i--) {
switch (k) {
case 0:
re = BB[7] + re;
break;
case 4:
if (!new RegExp("0{4}\\d{" + (a[0].length - i - 1) + "}$").test(a[0]))
re = BB[4] + re;
break;
case 8:
re = BB[5] + re;
BB[7] = BB[5];
k = 0;
break;
}
if (k % 4 == 2 && a[0].charAt(i + 2) != 0 && a[0].charAt(i + 1) == 0) re = AA[0] + re;
if (a[0].charAt(i) != 0) re = AA[a[0].charAt(i)] + BB[k % 4] + re;
k++;
}
if (a.length > 1) //加上小数部分(如果有小数部分)
{
re += BB[6];
for (var i = 0; i < a[1].length; i++) re += AA[a[1].charAt(i)];
}
return re;
}
7.延迟执行和只执行一次函数
// 延迟执行
async sleep(t) {
return new Promise((resolve) => setTimeout(resolve, t));
},
//只执行一次函数
onceFunction(fn) {
let onceFlag = false
return function() {
if (!onceFlag) {
onceFlag = true
fn.apply(this, arguments)
}
}
},
8.判断多个对象键值对是否相等
isEqual: function(...objects) {
return objects.every(obj => JSON.stringify(obj) === JSON.stringify(objects[0]))
},