项目中常用工具函数总结

mac2025-05-24  58

项目中常用工具函数总结:

1.判断是不是数组
Array.prototype.isPrototypeOf([]) //true
2.判断是否为空值
function isEmpty(val) { return val === undefined || val === null || val.length === 0 || val === " " }
3.判断是否为数组
function isArray(obj){ return Object.prototype.toString.call(obj)==="[object Array]" }
4.日期格式化
function formatDate(time, split) { const year = time.getFullYear(); const month = time.getMonth() + 1 < 10 ? "0" + (time.getMonth() + 1) : time.getMonth() + 1; const date = time.getDate() < 10 ? "0" + (time.getDate()) : time.getDate(); return [year,month,date].join(split || "") } //调用 let r = formatDate(new Date(),"/") console.log(r) // 2019/10/29
5.隐藏信息(手机号,身份证等脱敏)
function hideInfo(str, start, end, reverse) { if (!str) { return str; } var reStart = 0; var reEnd = 0; if (end === null) { if (!reverse) { reStart = start; reEnd = str.length - 1; } else { reStart = 0; reEnd = str.length - start; } } else { if (!reverse) { reStart = start; reEnd = end; } else { reStart = str.length - end; reEnd = str.length - start; } } if(reEnd-reStart>=0 && reEnd<str.length){ for(let i = reStart;i<=reEnd;i++){ let temp = str.split("") temp.splice(i,1,"*"); str=temp.join("") } return str } if(reEnd>=str.length){ for(var i = reStart;i<str.length;i++){ var temp = str.split(""); temp.splice(i,1,"*"); str = temp.join("") } } return str; }
6.数字加千分符
function separateThousands(srcNumber) { if (srcNumber === undefined || srcNumber === null) { return "" } return srcNumber.toString().replace(/^(-?[0-9]+)(?=\.|$)/,function(matchStr){ return matchStr.replace(/([0-9]+?)(?=(?:[0-9]{3})+$)/g,"$1,") }) }
7.是否是数字
function isNumeric(src){ return src-parseFloat(src) >=0 }
8.是否是一个整数
function isInteger(src){ //先判断是不是数字 if(isNumeric(src)){ if(src.toString().match(/^-?[0-9]+$/)){ return true; } } return false; }
9.获取对象子集或孙子级的值
function getKey(obj,key){ const keys = key.split(".") const currentKey = keys.shift(); if(!obj[currentKey]){ return undefined } if(!keys.length){ return obj[currentKey] } return getKey(obj[currentKey],keys.join(".")) } getKey({a:100,b:{c:300}},"b.c") //300

10.将两个数组合并为一个对象

let arr1 = ["a","b","c"] let arr2 = ["hello","world","love"] let result = arr2.reduce((memo,value,index)=>{ memo[arr1[index]]=value return memo },{}) //{a: "hello", b: "world", c: "love"}
最新回复(0)