js项目常用方法集合

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);
}

个人集成方法集合~   后续持续更新

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

白开水丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值