前端项目常用函数方法
2022-09-15 本文已影响0人
懒惰的狮子
随机生成UID
export const getUUID = () => {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
})
}
上传图片对图片进行压缩
export const uploadHandle = (file: File) => {
// 判断文件大小是否大于10MB,小于则不做处理
if (file.size > 10485760) return Toast.show({ icon: 'fail', content: '图片文件最大10M' })
// 返回一个promise对象
return new Promise(resolve => {
// 用于读取本地文件的对象
const reader = new FileReader()
// 用于存储选中图片的基本信息
const image: any = new Image()
image.onload = (imageEvent: any) => {
// 创建canvas标签元素
const canvas = document.createElement('canvas')
// 制定绘制的类型 这边指定的是2d类型
const context: any = canvas.getContext('2d')
// imgQuality 指缩放的比例,我这边设置了0.5,最好用变量去定义,这样容易维护
const width = image.width * 0.5 // 0.5
const height = image.height * 0.5 // 0.5
canvas.width = width
canvas.height = height
// 清除canvas的矩形内容(将canvas上的东西清除)
context.clearRect(0, 0, width, height)
// 在canvas中,按指定的比例去画出图片
context.drawImage(image, 0, 0, width, height)
// 将canvas画出的图片转成base64
const dataUrl = canvas.toDataURL(file.type)
// 把base64 dataUrl格式转换成blob类型(dataUrlToBlob方法在下面)
const blobData = dataUrlToBlob(dataUrl, file.type)
// 返回blobData进行上传
resolve(blobData)
}
// 读取完文件后,将图片的路径存到新建的image上
reader.onload = ((e: any) => { image.src = e.target.result })
// 根据路径读取选中的文件
reader.readAsDataURL(file)
})
}
const dataUrlToBlob = (dataUrl: any, type: any) => {
// 使用window的atob方法去解码base64
let binary = atob(dataUrl.split(',')[1])
let arr = []
// 转unicode编码
for (let i = 0; i < binary.length; i++) {
arr.push(binary.charCodeAt(i))
}
// 通过unicode编码去创建Blob类型
return new Blob([new Uint8Array(arr)], { type })
}
图片上传失败,单个图片重新上传
const filesUpload = (file: any) => {
const formData = new FormData()
formData.append('file', file.originFileObj)
上传图片接口.(formData, (res: any) => {
if (res.data.data) {
console.log('fileList是图片集合')
fileList.forEach((item: any, index: any) => {
if (item.uid === file.uid) { // 判断原集合和失败的id是否相同,删除原先集合失败对象
res.data.data.status = "done"
res.data.data.thumbUrl = "接口返回的url"
res.data.data.response = { data: res.data.data }
res.data.data.uid = '随机UID'
fileList.splice(index, 1, res.data.data)
}
})
setFileList([...fileList]) // 进行重新赋值,渲染页面。
} else {
console.log('上传失败')
}
});
}
获取当前时间
export const getNowFormatDate = () => {
let date = new Date();
let month: any = date.getMonth() + 1;
let strDate: any = date.getDate();
let hh: any = date.getHours();
let mm: any = date.getMinutes();
let ss: any = date.getSeconds();
if (month >= 1 && month <= 9) month = "0" + month;
if (strDate >= 0 && strDate <= 9) strDate = "0" + strDate;
if (hh >= 0 && hh <= 9) hh = "0" + hh;
if (mm >= 0 && mm <= 9) mm = "0" + mm;
if (ss >= 0 && ss <= 9) ss = "0" + ss;
let currentdate = date.getFullYear() + '-' + month + '-' + strDate + " " + hh + ':' + mm + ':' + date.getSeconds();
return currentdate;
}
时间转时间戳
// Date.parse() 不推荐使用毫秒数改成000显示
Date.parse(new Date()) // 当前时间
Date.parse("2017/03/19") // 自定义时间
// Date.getTime()推荐
let date = new Date();
let ff = date.getTime();
new Date()).valueOf() // 推荐
邮箱
export const isEmail = (s) => {
return /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(s)
}
手机号码
export const isMobile = (s) => {
return /^1[0-9]{10}$/.test(s)
}
电话号码
export const isPhone = (s) => {
return /^([0-9]{3,4}-)?[0-9]{7,8}$/.test(s)
}
检测字符串是否为空
export const isString = (string) => {
if ((string ?? "") !== "") {
return true
} else {
return false
}
}
检测是否是数组并且数组是否为空
export const isArrayEmpty = (arr) => {
if (Array.isArray(arr) && arr.length) {
return true
} else {
return false
}
}
检测是否是对象
export const isObject = (obj) => {
return Object.prototype.toString.call(obj) === '[object Object]';
};
检测是否是数组
export const isArray = (arr) => {
return Object.prototype.toString.call(arr) === '[object Array]';
};
检测是否是数组
export const isArray = (arr) => {
return Object.prototype.toString.call(arr) === '[object Array]';
};
单个数组去重
export const singleArrayDuplication = arr => [...new Set(arr)]
单个数组对象去重
export const arrayReduce = (arr, key) => {
const data = []
arr.forEach((el, index) => {
arr.findIndex(ele => ele[key] == el[key]) == index && data.push(el)
});
return data
}
多个数组合并并去重
export const arrayConcat = (...arr) => {
return singleArrayDuplication(arr.join(",").split(","))
}
多个数组对象合并并去重
export const arrayMultipleConcat = (key, ...arr) => {
const data = []
arr.forEach(it => {
if (isArray(it)) {
it.forEach(ite => {
data.push(ite)
})
}
})
return arrayReduce(data, key)
}
检测对象是否存在该属性
export const objectHasOwn = (object, key) => {
return Object.hasOwn(object, key)
}
比较两个数组的差异,并返回差异值
export const getArrDifference = (beforeArr, afterArr) => {
return beforeArr.concat(afterArr).filter((v, i, arr) => {
return arr.indexOf(v) === arr.lastIndexOf(v);
});
}
获取url参数
export const getQueryString = (name) => {
const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
const search = window.location.search.split('?')[1] || '';
const r = search.match(reg) || [];
return r[2];
}
获取hash模式url参数
export const getQueryString = (name) => {
const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
const search = window.location.hash.split('?')[1] || '';
const r = search.match(reg) || [];
return r[2];
}
滚动到顶部
export const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
}
随机数范围
export const random = (min, max) => {
if (arguments.length === 2) {
return Math.floor(min + Math.random() * ((max + 1) - min))
} else {
return null;
}
}
将阿拉伯数字翻译成中文的大写数字
export const numberToChinese = (num) => {
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)];
}
if (re == '一十')
re = "十";
if (re.match(/^一/) && re.length == 3)
re = re.replace("一", "");
return re;
}
将数字转换为大写金额
export const changeToChinese = (Num) => {
//判断如果传递进来的不是字符的话转换为字符
if (typeof Num == "number") {
Num = new String(Num);
};
Num = Num.replace(/,/g, "") //替换tomoney()中的“,”
Num = Num.replace(/ /g, "") //替换tomoney()中的空格
Num = Num.replace(/¥/g, "") //替换掉可能出现的¥字符
if (isNaN(Num)) { //验证输入的字符是否为数字
//alert("请检查小写金额是否正确");
return "";
};
//字符处理完毕后开始转换,采用前后两部分分别转换
var part = String(Num).split(".");
var newchar = "";
//小数点前进行转化
for (var i = part[0].length - 1; i >= 0; i--) {
if (part[0].length > 10) {
return "";
//若数量超过拾亿单位,提示
}
var tmpnewchar = ""
var perchar = part[0].charAt(i);
switch (perchar) {
case "0":
tmpnewchar = "零" + tmpnewchar;
break;
case "1":
tmpnewchar = "壹" + tmpnewchar;
break;
case "2":
tmpnewchar = "贰" + tmpnewchar;
break;
case "3":
tmpnewchar = "叁" + tmpnewchar;
break;
case "4":
tmpnewchar = "肆" + tmpnewchar;
break;
case "5":
tmpnewchar = "伍" + tmpnewchar;
break;
case "6":
tmpnewchar = "陆" + tmpnewchar;
break;
case "7":
tmpnewchar = "柒" + tmpnewchar;
break;
case "8":
tmpnewchar = "捌" + tmpnewchar;
break;
case "9":
tmpnewchar = "玖" + tmpnewchar;
break;
}
switch (part[0].length - i - 1) {
case 0:
tmpnewchar = tmpnewchar + "元";
break;
case 1:
if (perchar != 0) tmpnewchar = tmpnewchar + "拾";
break;
case 2:
if (perchar != 0) tmpnewchar = tmpnewchar + "佰";
break;
case 3:
if (perchar != 0) tmpnewchar = tmpnewchar + "仟";
break;
case 4:
tmpnewchar = tmpnewchar + "万";
break;
case 5:
if (perchar != 0) tmpnewchar = tmpnewchar + "拾";
break;
case 6:
if (perchar != 0) tmpnewchar = tmpnewchar + "佰";
break;
case 7:
if (perchar != 0) tmpnewchar = tmpnewchar + "仟";
break;
case 8:
tmpnewchar = tmpnewchar + "亿";
break;
case 9:
tmpnewchar = tmpnewchar + "拾";
break;
}
var newchar = tmpnewchar + newchar;
}
//小数点之后进行转化
if (Num.indexOf(".") != -1) {
if (part[1].length > 2) {
// alert("小数点之后只能保留两位,系统将自动截断");
part[1] = part[1].substr(0, 2)
}
for (i = 0; i < part[1].length; i++) {
tmpnewchar = ""
perchar = part[1].charAt(i)
switch (perchar) {
case "0":
tmpnewchar = "零" + tmpnewchar;
break;
case "1":
tmpnewchar = "壹" + tmpnewchar;
break;
case "2":
tmpnewchar = "贰" + tmpnewchar;
break;
case "3":
tmpnewchar = "叁" + tmpnewchar;
break;
case "4":
tmpnewchar = "肆" + tmpnewchar;
break;
case "5":
tmpnewchar = "伍" + tmpnewchar;
break;
case "6":
tmpnewchar = "陆" + tmpnewchar;
break;
case "7":
tmpnewchar = "柒" + tmpnewchar;
break;
case "8":
tmpnewchar = "捌" + tmpnewchar;
break;
case "9":
tmpnewchar = "玖" + tmpnewchar;
break;
}
if (i == 0) tmpnewchar = tmpnewchar + "角";
if (i == 1) tmpnewchar = tmpnewchar + "分";
newchar = newchar + tmpnewchar;
}
}
//替换所有无用汉字
while (newchar.search("零零") != -1)
newchar = newchar.replace("零零", "零");
newchar = newchar.replace("零亿", "亿");
newchar = newchar.replace("亿万", "亿");
newchar = newchar.replace("零万", "万");
newchar = newchar.replace("零元", "元");
newchar = newchar.replace("零角", "");
newchar = newchar.replace("零分", "");
if (newchar.charAt(newchar.length - 1) == "元") {
newchar = newchar + "整"
}
return newchar;
}