1.价格格式化
export function moneyFilter(val){
if(!val||val==0){
return "0.00"
}
val = Math.floor(Number(val)*100+0.500001)
let decimalStr = val%100
if(decimalStr<10){
decimalStr = "0"+decimalStr
}
let integerStr =String(Math.floor(val/100))
let len = integerStr.length
let newStr = ""
for(var i = 0; i < Math.ceil(len/3); i++) {
newStr=integerStr.substring(len-(3*i),len-(3*(i+1)))+(i>0?","+newStr:newStr)
}
return newStr+"."+decimalStr
}
2.字符串转数字
export function toNumber(str){
var str = str.split("")
str = str.map(item=>+item)
var num = str.reduce((x,y)=>{
return x*10+y
})
return num
}
3.利用reduce()求积:
export function quadrature(arr){
pow(x,y){
return arr.reduce((x,y)=>x*y);
}
}
4.首字母大写其他小写
export function normalize(arr) {
return arr.map(item=>{
return item.split("")[0].toUpperCase()+item.split("").slice(1).reduce((x,y)=>{
return x.toLowerCase() + y.toLowerCase()
})
} )
}
5.数组去重
1)方法一:
export function duplicateRemovalArr(arr){
return arr.filter((element,index,arr)=>{
return self.indexOf(element) === index
})
}
2)方法二:
var arr = [1,2,1,1,2,3,4,5,5]
arr = [...new Set(arr)]
3)方法三:
export function duplicateRemovalArr(arr){
arr = new Set(arr)
return Array.from(arr)
}
6.字符串去重
function duplicateRemovalString(str){
return [...new Set(str)].join("")
}
7.时间戳转日期时间格式
/**
* 格式化时间
* @param timeTemp 时间戳
* @param formatStr 格式化类型
* @returns
*/
export const formatTimerDetail = (timeTemp, rule= 'YYYY-MM-DD HH:mm:ss') => {
if (!timeTemp) return "";
// timeTemp是整数,否则要parseInt转换
const temp = parseInt(String(timeTemp));
let formatRule = rule
const time = new Date(temp);
const year = time.getFullYear();
const month = time.getMonth() + 1;
const day = time.getDate();
const hours = time.getHours();
const minutes = time.getMinutes();
const seconds = time.getSeconds();
let newRule = '';
let formatKeys = []
if(formatRule.includes('*')){
const chineseRule:{[key:string]:string} = {
YYYY:'年',
MM:'月',
DD:'日',
HH:'时',
mm:'分',
ss:'秒',
}
formatKeys = formatRule.split('*')
formatKeys.forEach((item, idx) => {
if(idx < formatKeys.length){
newRule += `${item}${ chineseRule[item] ? chineseRule[item] : '' }`
}
})
formatRule = newRule
}
return formatRule.replace('YYYY', String(year))
.replace('MM', padStart(month))
.replace('DD', padStart(day))
.replace('HH', padStart(hours))
.replace('mm', padStart(minutes))
.replace('ss', padStart(seconds))
}
8.创建指定时间后 resolve 的 Promise
export function delay(timespan = 0) {
return new Promise(resolve => setTimeout(resolve, timespan));
}
9.生成随机数
function randombetween(min, max){
return min + (Math.random() * (max-min +1));
}
11.拷贝数组、对象
function copy(data){
//新数组、对象改变不改变拷贝对象
return JSON.parse(JSON.stringify(data))
}
12.中文、符号、字母、数字混合排序
/**
* 数据排序 // 本次改动提交 是由老李确认并且认可的情况下修改的
* @param {* Array } arr 需要排序的数组
* @param {* String } field 排序字段
* @param {* String } order 排序方式 desc || asc
* @returns Array
*/
export const sortArray = (arr, field, order = 'asc') => {
// 汉字开头
const chineseReg = new RegExp('^[\u4e00-\u9fa5]')
let wordArr = []
let noWordArr = []
let isAsc = order === 'asc'
const collatorCN = new Intl.Collator('zh-CN');
const collatorUC = new Intl.Collator('en-US');
arr.forEach(item => {
if (chineseReg.test(item[field]) && field) wordArr.push(item)
else if (chineseReg.test(item)) wordArr.push(item)
else noWordArr.push(item)
})
if (field) {
wordArr = wordArr.sort((pre, next) => {
if (isAsc) return collatorCN.compare(pre[field] ?? '',next[field] ?? '')
else return collatorCN.compare(next[field] ?? '',pre[field] ?? '')
})
noWordArr = noWordArr.sort((pre, next) => {
if(field === 'ord') {
if (isAsc) return (pre[field] ?? '') - (next[field] ?? '')
else return (next[field] ?? '') - (pre[field] ?? '')
} else {
if (isAsc) return collatorUC.compare(pre[field] ?? '',next[field] ?? '')
else return collatorUC.compare(next[field] ?? '',pre[field] ?? '')
}
})
} else {
wordArr = wordArr.sort((pre, next) => {
if (isAsc) return collatorCN.compare(pre,next)
else return collatorCN.compare(next,pre)
})
noWordArr = noWordArr.sort((a,b) => {
if (isAsc) return collatorUC.compare(a,b)
else return collatorUC.compare(b,a)
})
}
let sortRelust = isAsc ? [...noWordArr, ...wordArr] : [...wordArr, ...noWordArr]
return sortRelust
}
13. 号码中间隐藏
export const formatPhone = (phone)=> {
if (!phone) return "--";
return String(phone).replace(/(^\d{3})(\d{4})(\d{4}$)/, "$1****$2");
}
14. 补零
export const padStart = (data) => {
return data < 10 ? `0${data}` : String(data);
}
个人集成方法集合~ 后续持续更新