javascript 常用工具类
数组
判断是否是数组
export const arrJudge = (arr) => {
if (Array.isArray(arr)) {
return true
}
}
数组去重
export const arrRemoveRepeat = (arr) => {
return Array.from(new Set(arr))
}
数组对象去重
export const mergeArray = (arr1, arr2) => {
const cloneArr1 = arr1.slice(0)
let v
for (let i = 0; i < arr2.length; i++) {
v = arr2[i]
if (~cloneArr1.findIndex((el) => el.id === v.id)) {
continue
}
cloneArr1.push(v)
}
return cloneArr1
}
数组排序
export const arrOrderAscend = (arr, ascendFlag = true) => {
return arr.sort((a, b) => {
return ascendFlag ? a - b : b - a
})
}
数组最大值
export const arrMax = (arr) => {
return Math.max(...arr)
}
数组求和
export const arrSum = (arr) => {
return arr.reduce((prev, cur) => {
return prev + cur
}, 0)
}
数组对象求和
export const arrObjSum = (obj, key) => {
return arrObj.reduce((prev, cur) => prev + cur.key, 0)
}
数组合并,目前合并一维
export const arrConcat = (arrOne, arrTwo) => {
return [...arrOne, ...arrTwo]
}
数组是否包含某值
export const arrIncludeValue = (arr, value) => {
return arr.includes(value)
}
数组并集,只支持一维数组
export const arrAndSet = (arrOne, arrTwo) => {
return arrOne.concat(arrTwo.filter((v) => !arrOne.includes(v)))
}
数组交集,只支持一维数组
export const arrIntersection = (arrOne, arrTwo) => {
return arrOne.filter((v) => arrTwo.includes(v))
}
数组差集,只支持一维数组
export const arrDifference = (arrOne, arrTwo) => {
return arrOne
.concat(arrTwo)
.filter((v) => !arrOne.includes(v) || !arrTwo.includes(v))
}
两个数组合并成一个对象数组,考虑到复杂度,所以目前支持两个一维数组
export const arrTwoToArrObj = (arrOne, arrTwo, oneKey, twoKey) => {
if (!oneKey && !twoKey) {
return arrOne.map((oneKey, i) => ({ [oneKey]: arrTwo[i] }))
} else {
return arrOne.map((oneKey, i) => ({ oneKey, twoKey: arrTwo[i] }))
}
}
将对象转化为对象数组
export const objToArr = (objData) => {
var arr = []
for (let i in objData) {
let o = {}
o[i] = obj[i]
arr.push(o)
}
return arr
}
多数组相加
export const arrTotalArray = (arr) => {
let result = []
for (let i = 0; i < arr.length; i++) {
arr[i].forEach((value, index) => {
if (result[index] == null || result[index] == '') {
result[index] = 0
}
result[index] += parseInt(value)
})
}
return result
}
优化高频率执行代码
节流
export const throttle = function (func, delay) {
let timer = null
return function () {
if (!timer) {
timer = setTimeout(() => {
func.apply(this, arguments)
timer = null
}, delay)
}
}
}
防抖
export const debounce = function (fn, wait) {
let timeout = null
return function () {
if (timeout !== null) clearTimeout(timeout)
timeout = setTimeout(() => {
fn.apply(this, arguments)
timeout = null
}, wait)
}
}
URL
获取 url 后面通过?传参的参数
export function getQueryString(name) {
const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
const url = window.location.href
const search = url.substring(url.lastIndexOf('?') + 1)
const r = search.match(reg)
if (r != null) return unescape(r[2])
return null
}
url 参数转对象
export function parseQueryString(url) {
url = !url ? window.location.href : url
if (url.indexOf('?') === -1) {
return {}
}
var search =
url[0] === '?' ? url.substr(1) : url.substring(url.lastIndexOf('?') + 1)
if (search === '') {
return {}
}
search = search.split('&')
var query = {}
for (var i = 0; i < search.length; i++) {
var pair = search[i].split('=')
query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '')
}
return query
}
正则
判断是否是数字
export const checkNum = (data) => {
const reg = /^\d{1,}$/g
if (reg.test(data)) return true
}
判断是否是字母
export const checkLetter = (data) => {
const reg = /^[a-zA-Z]+$/g
if (reg.test(data)) return true
}
判断是否全部是小写字母
export const checkLowercaseLetter = (data) => {
const reg = /^[a-z]+$/g
if (reg.test(data)) return true
}
判断是否是大写字母
export const checkCapitalLetter = (data) => {
const reg = /^[A-Z]+$/g
if (reg.test(data)) return true
}
判断是否是字母或数字
export const checkNumOrLetter = (data) => {
const reg = /^[0-9a-zA-Z]*$/g
if (reg.test(data)) return true
}
判断是否是中文
export const checkChinese = (data) => {
const reg = /^[\u4E00-\u9FA5]+$/g
if (reg.test(data)) return true
}
判断是否是中文,数字或字母
export const checkChineseNumberLettter = (data) => {
const reg = /^[a-zA-Z0-9\u4e00-\u9fa5]+$/g
if (reg.test(data)) return true
}
判断是否是邮箱地址
export const checkEmail = (data) => {
const reg =
/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/g
if (reg.test(data)) return true
}
判断是否是手机号
export const checkTelphone = (data) => {
const reg = /^((\+|00)86)?1[3-9]\d{9}$/g
if (reg.test(data)) return true
}
判断是否是正确的网址
export const checkUrl = (url) => {
const a = document.createElement('a')
a.href = url
return (
[
/^(http|https):$/.test(a.protocol),
a.host,
a.pathname !== url,
a.pathname !== `/${url}`
].find((x) => !x) === undefined
)
}
判断是否为 16 进制颜色
export const isColor = (str) => {
return /^(#([0-9a-fA-F]{3}){1,2}|[rR][gG][Bb](\((\s*(2[0-4]\d|25[0-5]|[01]?\d{1,2})\s*,){2}\s*(2[0-4]\d|25[0-5]|[01]?\d{1,2})\s*\)|[Aa]\((\s*(2[0-4]\d|25[0-5]|[01]?\d{1,2})\s*,){3}\s*([01]|0\.\d+)\s*\)))$/.test(
str
)
}
判断是否为身份证号
export const isIdCard = (str) => {
return /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/.test(
str
)
}
客户端环境检测
判断是浏览器内核
export const checkBrowser = () => {
const u = navigator.userAgent
const obj = {
trident: u.indexOf('Trident') > -1,
presto: u.indexOf('Presto') > -1,
webKit: u.indexOf('AppleWebKit') > -1,
gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1
}
return Object.keys(obj)[Object.values(obj).indexOf(true)]
}
判断是终端类型,值有 ios,android,iPad
export const checkIosAndroidIpad = () => {
const u = navigator.userAgent
const obj = {
ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1,
iPad: u.indexOf('iPad') > -1
}
return Object.keys(obj)[Object.values(obj).indexOf(true)]
}
判断是否是微信,qq 或 uc
export const checkWeixinQqUc = () => {
const u = navigator.userAgent
const obj = {
weixin: u.indexOf('MicroMessenger') > -1,
qq: u.match(/QQ/i) == 'qq' && !u.indexOf('MQQBrowser') > -1,
uc: u.indexOf('UCBrowser') > -1
}
return Object.keys(obj)[Object.values(obj).indexOf(true)]
}
检查是否是 IphoneX
export const checkIsIphoneX = () => {
const u = navigator.userAgent
const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
if (isIOS && screen.height >= 812) {
return true
}
}
判断浏*览器是否支持 webP 格式图片
export const isSupportWebP = () => {
return (
!![].map &&
document
.createElement('canvas')
.toDataURL('image/webp')
.indexOf('data:image/webp') == 0
)
}
时间/日期
获取年份
export const getYear = () => {
return new Date().getFullYear()
}
获取当前月份
export const getMonth = (fillFlag = true) => {
const mon = new Date().getMonth() + 1
const monRe = mon
if (fillFlag) mon < 10 ? `0${mon}` : mon
return monRe
}
获取日
export const getDay = (fillFlag = true) => {
const day = new Date().getDate()
const dayRe = day
if (fillFlag) day < 10 ? `0${day}` : day
return dayRe
}
获取星期几
export const getWhatDay = () => {
return new Date().getDay() ? new Date().getDay() : 7
}
获取当前月天数
export const getMonthNum = (year, month) => {
var d = new Date(year, month, 0)
return d.getDate()
}
获取当前时间 yyyy-mm-dd,hh:mm:ss
export const getYyMmDdHhMmSs = () => {
const date = new Date()
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hours = date.getHours()
const minu = date.getMinutes()
const second = date.getSeconds()
const arr = [month, day, hours, minu, second]
arr.forEach((item) => {
item < 10 ? '0' + item : item
})
return (
year +
'-' +
arr[0] +
'-' +
arr[1] +
' ' +
arr[2] +
':' +
arr[3] +
':' +
arr[4]
)
}
时间戳转化为年月日
function getzf(time) {
return +time < 10 ? `0${time}` : time
}
export const timesToYyMmDd = (times, ymd, hms) => {
const oDate = new Date(times)
const oYear = oDate.getFullYear()
const oMonth = oDate.getMonth() + 1
const oDay = oDate.getDate()
const oHour = oDate.getHours()
const oMin = oDate.getMinutes()
const oSec = oDate.getSeconds()
let oTime
switch (ymd) {
case 'yyyy-mm-dd':
oTime = oYear + '-' + getzf(oMonth) + '-' + getzf(oDay)
break
case 'yyyy/mm/dd':
oTime = oYear + '/' + getzf(oMonth) + '/' + getzf(oDay)
break
}
switch (hms) {
case 'hh':
oTime = ' ' + oTime + getzf(oHour)
break
case 'hh:mm':
oTime = oTime + getzf(oHour) + ':' + getzf(oMin)
break
case 'hh:mm:ss':
oTime = oTime + getzf(oHour) + ':' + getzf(oMin) + ':' + getzf(oSec)
break
}
return oTime
}
将年月日转化成时间戳
export const YyMmDdToTimes = (time) => {
return new Date(time.replace(/-/g, '/')).getTime()
}
比较时间 1 小于时间 2
export const compareTimeOneLessTwo = (timeOne, timeTwo) => {
return (
new Date(timeOne.replace(/-/g, '/')).getTime() <
new Date(timeTwo.replace(/-/g, '/')).getTime()
)
}
时间戳转化为年月日
export const formatPassTime = (startTime) => {
const currentTime = Date.parse(new Date()),
time = currentTime - startTime,
day = parseInt(time / (1000 * 60 * 60 * 24)),
hour = parseInt(time / (1000 * 60 * 60)),
min = parseInt(time / (1000 * 60)),
month = parseInt(day / 30),
year = parseInt(month / 12)
if (year) return year + '年前'
if (month) return month + '个月前'
if (day) return day + '天前'
if (hour) return hour + '小时前'
if (min) return min + '分钟前'
else return '刚刚'
}
格式化现在距${endTime}的剩余时间
export const formatRemainTime = (endTime) => {
var startDate = new Date()
var endDate = new Date(endTime)
var t = endDate.getTime() - startDate.getTime()
var d = 0,
h = 0,
m = 0,
s = 0
if (t >= 0) {
d = Math.floor(t / 1000 / 3600 / 24)
h = Math.floor((t / 1000 / 60 / 60) % 24)
m = Math.floor((t / 1000 / 60) % 60)
s = Math.floor((t / 1000) % 60)
}
return d + '天 ' + h + '小时 ' + m + '分钟 ' + s + '秒'
}
判断是否为同一天
export const isSameDay = (date1, date2) => {
if (!date2) {
date2 = new Date()
}
var date1_year = date1.getFullYear(),
date1_month = date1.getMonth() + 1,
date1_date = date1.getDate()
var date2_year = date2.getFullYear(),
date2_month = date2.getMonth() + 1,
date2_date = date2.getDate()
return (
date1_date === date2_date &&
date1_month === date2_month &&
date1_year === date2_year
)
}
计算${startTime - endTime}的剩余时间
export const timeLeft = (startTime, endTime) => {
if (!startTime || !endTime) {
return
}
var startDate, endDate
if (startTime instanceof Date) {
startDate = startTime
} else {
startDate = new Date(startTime.replace(/-/g, '/'))
}
if (endTime instanceof Date) {
endDate = endTime
} else {
endDate = new Date(endTime.replace(/-/g, '/'))
}
var t = endDate.getTime() - startDate.getTime()
var d = 0,
h = 0,
m = 0,
s = 0
if (t >= 0) {
d = Math.floor(t / 1000 / 3600 / 24)
h = Math.floor((t / 1000 / 60 / 60) % 24)
m = Math.floor((t / 1000 / 60) % 60)
s = Math.floor((t / 1000) % 60)
}
return { d, h, m, s }
}