1. 数字操作
(1)生成指定范围随机数
export const randomNum = ( min, max ) => Math. floor ( Math. random ( ) * ( max - min + 1 ) ) + min
(2)数字千分位分隔
export const format = ( n ) => {
let num = n. toString ( ) ;
let len = num. length;
if ( len <= 3 ) {
return num;
} else {
let temp = '' ;
let remainder = len % 3 ;
if ( remainder > 0 ) {
return num. slice ( 0 , remainder) + ',' + num. slice ( remainder, len) . match ( / \d{3} / g ) . join ( ',' ) + temp;
} else {
return num. slice ( 0 , len) . match ( / \d{3} / g ) . join ( ',' ) + temp;
}
}
}
2. 数组操作
(1)数组乱序
export const arrScrambling = ( arr ) => {
for ( let i = 0 ; i < arr. length; i++ ) {
const randomIndex = Math. round ( Math. random ( ) * ( arr. length - 1 - i) ) + i;
[ arr[ i] , arr[ randomIndex] ] = [ arr[ randomIndex] , arr[ i] ] ;
}
return arr;
}
(2)数组扁平化
export const flatten = ( arr ) => {
let result = [ ] ;
for ( let i = 0 ; i < arr. length; i++ ) {
if ( Array. isArray ( arr[ i] ) ) {
result = result. concat ( flatten ( arr[ i] ) ) ;
} else {
result. push ( arr[ i] ) ;
}
}
return result;
}
(3)数组中获取随机数
export const sample = arr => arr[ Math. floor ( Math. random ( ) * arr. length) ] ;
3. 字符串操作
(1)生成随机字符串
export const randomString = ( len ) => {
let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789' ;
let strLen = chars. length;
let randomStr = '' ;
for ( let i = 0 ; i < len; i++ ) {
randomStr += chars. charAt ( Math. floor ( Math. random ( ) * strLen) ) ;
}
return randomStr;
} ;
(2)字符串首字母大写
export const fistLetterUpper = ( str ) => {
return str. charAt ( 0 ) . toUpperCase ( ) + str. slice ( 1 ) ;
} ;
(3)手机号中间四位变成*
export const telFormat = ( tel ) => {
tel = String ( tel) ;
return tel. substr ( 0 , 3 ) + "****" + tel. substr ( 7 ) ;
} ;
(4)驼峰命名转换成短横线命名
export const getKebabCase = ( str ) => {
return str. replace ( / [A-Z] / g , ( item ) => '-' + item. toLowerCase ( ) )
}
(5)短横线命名转换成驼峰命名
export const getCamelCase = ( str ) => {
return str. replace ( / -([a-z]) / g , ( i, item ) => item. toUpperCase ( ) )
}
(6)全角转换为半角
export const toCDB = ( str ) => {
let result = "" ;
for ( let i = 0 ; i < str. length; i++ ) {
code = str. charCodeAt ( i) ;
if ( code >= 65281 && code <= 65374 ) {
result += String. fromCharCode ( str. charCodeAt ( i) - 65248 ) ;
} else if ( code == 12288 ) {
result += String. fromCharCode ( str. charCodeAt ( i) - 12288 + 32 ) ;
} else {
result += str. charAt ( i) ;
}
}
return result;
}
(7)半角转换为全角
export const toDBC = ( str ) => {
let result = "" ;
for ( let i = 0 ; i < str. length; i++ ) {
code = str. charCodeAt ( i) ;
if ( code >= 33 && code <= 126 ) {
result += String. fromCharCode ( str. charCodeAt ( i) + 65248 ) ;
} else if ( code == 32 ) {
result += String. fromCharCode ( str. charCodeAt ( i) + 12288 - 32 ) ;
} else {
result += str. charAt ( i) ;
}
}
return result;
}
4. 格式转化
(1)数字转化为大写金额
export const digitUppercase = ( n ) => {
const fraction = [ '角' , '分' ] ;
const digit = [
'零' , '壹' , '贰' , '叁' , '肆' ,
'伍' , '陆' , '柒' , '捌' , '玖'
] ;
const unit = [
[ '元' , '万' , '亿' ] ,
[ '' , '拾' , '佰' , '仟' ]
] ;
n = Math. abs ( n) ;
let s = '' ;
for ( let i = 0 ; i < fraction. length; i++ ) {
s += ( digit[ Math. floor ( n * 10 * Math. pow ( 10 , i) ) % 10 ] + fraction[ i] ) . replace ( / 零. / , '' ) ;
}
s = s || '整' ;
n = Math. floor ( n) ;
for ( let i = 0 ; i < unit[ 0 ] . length && n > 0 ; i++ ) {
let p = '' ;
for ( let j = 0 ; j < unit[ 1 ] . length && n > 0 ; j++ ) {
p = digit[ n % 10 ] + unit[ 1 ] [ j] + p;
n = Math. floor ( n / 10 ) ;
}
s = p. replace ( / (零.)*零$ / , '' ) . replace ( / ^$ / , '零' ) + unit[ 0 ] [ i] + s;
}
return s. replace ( / (零.)*零元 / , '元' )
. replace ( / (零.)+ / g , '零' )
. replace ( / ^整$ / , '零元整' ) ;
} ;
(2)数字转化为中文数字
export const intToChinese = ( value ) => {
const str = String ( value) ;
const len = str. length- 1 ;
const idxs = [ '' , '十' , '百' , '千' , '万' , '十' , '百' , '千' , '亿' , '十' , '百' , '千' , '万' , '十' , '百' , '千' , '亿' ] ;
const num = [ '零' , '一' , '二' , '三' , '四' , '五' , '六' , '七' , '八' , '九' ] ;
return str. replace ( / ([1-9]|0+) / g , ( $, $1 , idx, full ) => {
let pos = 0 ;
if ( $1 [ 0 ] !== '0' ) {
pos = len- idx;
if ( idx == 0 && $1 [ 0 ] == 1 && idxs[ len- idx] == '十' ) {
return idxs[ len- idx] ;
}
return num[ $1 [ 0 ] ] + idxs[ len- idx] ;
} else {
let left = len - idx;
let right = len - idx + $1. length;
if ( Math. floor ( right / 4 ) - Math. floor ( left / 4 ) > 0 ) {
pos = left - left % 4 ;
}
if ( pos ) {
return idxs[ pos] + num[ $1 [ 0 ] ] ;
} else if ( idx + $1. length >= len ) {
return '' ;
} else {
return num[ $1 [ 0 ] ]
}
}
} ) ;
}
5. 操作存储
(1)存储loalStorage
export const loalStorageSet = ( key, value ) => {
if ( ! key) return ;
if ( typeof value !== 'string' ) {
value = JSON . stringify ( value) ;
}
window. localStorage. setItem ( key, value) ;
} ;
(2)获取localStorage
export const loalStorageGet = ( key ) => {
if ( ! key) return ;
return window. localStorage. getItem ( key) ;
} ;
(3)删除localStorage
export const loalStorageRemove = ( key ) => {
if ( ! key) return ;
window. localStorage. removeItem ( key) ;
} ;
(4)存储sessionStorage
export const sessionStorageSet = ( key, value ) => {
if ( ! key) return ;
if ( typeof value !== 'string' ) {
value = JSON . stringify ( value) ;
}
window. sessionStorage. setItem ( key, value)
} ;
(5)获取sessionStorage
export const sessionStorageGet = ( key ) => {
if ( ! key) return ;
return window. sessionStorage. getItem ( key)
} ;
(6)删除sessionStorage
export const sessionStorageRemove = ( key ) => {
if ( ! key) return ;
window. sessionStorage. removeItem ( key)
} ;
6. 操作cookie
(1)设置cookie
export const setCookie = ( key, value, expire ) => {
const d = new Date ( ) ;
d. setDate ( d. getDate ( ) + expire) ;
document. cookie = ` ${ key} = ${ value} ;expires= ${ d. toUTCString ( ) } `
} ;
(2)读取cookie
export const getCookie = ( key ) => {
const cookieStr = unescape ( document. cookie) ;
const arr = cookieStr. split ( '; ' ) ;
let cookieValue = '' ;
for ( let i = 0 ; i < arr. length; i++ ) {
const temp = arr[ i] . split ( '=' ) ;
if ( temp[ 0 ] === key) {
cookieValue = temp[ 1 ] ;
break
}
}
return cookieValue
} ;
(3)删除cookie
export const delCookie = ( key ) => {
document. cookie = ` ${ encodeURIComponent ( key) } =;expires= ${ new Date ( ) } `
} ;
7. 格式校验
(1)校验身份证号码
export const checkCardNo = ( value ) => {
let reg = / (^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$) / ;
return reg. test ( value) ;
} ;
(2)校验是否包含中文
export const haveCNChars => ( value ) => {
return / [\u4e00-\u9fa5] / . test ( value) ;
}
(3)校验是否为中国大陆的邮政编码
export const isPostCode = ( value ) => {
return / ^[1-9][0-9]{5}$ / . test ( value. toString ( ) ) ;
}
(4)校验是否为IPv6地址
export const isIPv6 = ( str ) => {
return Boolean ( str. match ( / : / g ) ? str. match ( / : / g ) . length<= 7 : false && / :: / . test ( str) ? / ^([\da-f]{1,4}(:|::)){1,6}[\da-f]{1,4}$ / i . test ( str) : / ^([\da-f]{1,4}:){7}[\da-f]{1,4}$ / i . test ( str) ) ;
}
(5)校验是否为邮箱地址
export const isEmail = ( value) {
return / ^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$ / . test ( value) ;
}
(6)校验是否为中国大陆手机号
export const isTel = ( value ) => {
return / ^1[3,4,5,6,7,8,9][0-9]{9}$ / . test ( value. toString ( ) ) ;
}
(7)校验是否包含emoji表情
export const isEmojiCharacter = ( value ) => {
value = String ( value) ;
for ( let i = 0 ; i < value. length; i++ ) {
const hs = value. charCodeAt ( i) ;
if ( 0xd800 <= hs && hs <= 0xdbff ) {
if ( value. length > 1 ) {
const ls = value. charCodeAt ( i + 1 ) ;
const uc = ( ( hs - 0xd800 ) * 0x400 ) + ( ls - 0xdc00 ) + 0x10000 ;
if ( 0x1d000 <= uc && uc <= 0x1f77f ) {
return true ;
}
}
} else if ( value. length > 1 ) {
const ls = value. charCodeAt ( i + 1 ) ;
if ( ls == 0x20e3 ) {
return true ;
}
} else {
if ( 0x2100 <= hs && hs <= 0x27ff ) {
return true ;
} else if ( 0x2B05 <= hs && hs <= 0x2b07 ) {
return true ;
} else if ( 0x2934 <= hs && hs <= 0x2935 ) {
return true ;
} else if ( 0x3297 <= hs && hs <= 0x3299 ) {
return true ;
} else if ( hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030
|| hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b
|| hs == 0x2b50 ) {
return true ;
}
}
}
return false ;
}
(8)正则相关的校验
export function isExternal ( path ) {
return / ^(https?:|mailto:|tel:) / . test ( path)
}
export function validUsername ( str ) {
return str. trim ( ) !== ''
}
export function validURL ( url ) {
const reg = / ^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$ /
return reg. test ( url)
}
export function validLowerCase ( str ) {
const reg = / ^[a-z]+$ /
return reg. test ( str)
}
export function validUpperCase ( str ) {
const reg = / ^[A-Z]+$ /
return reg. test ( str)
}
export function validAlphabets ( str ) {
const reg = / ^[A-Za-z]+$ /
return reg. test ( str)
}
export function validEmail ( email ) {
const reg = / ^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$ /
return reg. test ( email)
}
export function isString ( str ) {
if ( typeof str === 'string' || str instanceof String ) {
return true
}
return false
}
export function isArray ( arg ) {
if ( typeof Array. isArray === 'undefined' ) {
return Object . prototype. toString . call ( arg) === '[object Array]'
}
return Array. isArray ( arg)
}
8. 操作URL
(1)获取URL参数列表
export const GetRequest = ( ) => {
let url = location. search;
const paramsStr = / .+\?(.+)$ / . exec ( url) [ 1 ] ;
const paramsArr = paramsStr. split ( '&' ) ;
let paramsObj = { } ;
paramsArr. forEach ( param => {
if ( / = / . test ( param) ) {
let [ key, val] = param. split ( '=' ) ;
val = decodeURIComponent ( val) ;
val = / ^\d+$ / . test ( val) ? parseFloat ( val) : val;
if ( paramsObj. hasOwnProperty ( key) ) {
paramsObj[ key] = [ ] . concat ( paramsObj[ key] , val) ;
} else {
paramsObj[ key] = val;
}
} else {
paramsObj[ param] = true ;
}
} )
return paramsObj;
} ;
(2)检测URL是否有效
export const getUrlState = ( URL ) => {
let xmlhttp = new ActiveXObject ( "microsoft.xmlhttp" ) ;
xmlhttp. Open ( "GET" , URL , false ) ;
try {
xmlhttp. Send ( ) ;
} catch ( e) {
} finally {
let result = xmlhttp. responseText;
if ( result) {
if ( xmlhttp. Status == 200 ) {
return true ;
} else {
return false ;
}
} else {
return false ;
}
}
}
(3)键值对拼接成URL参数
export const params2Url = ( obj ) => {
let params = [ ]
for ( let key in obj) {
params. push ( ` ${ key} = ${ obj[ key] } ` ) ;
}
return encodeURIComponent ( params. join ( '&' ) )
}
(4)修改URL中的参数
export const replaceParamVal => ( paramName, replaceWith) {
const oUrl = location. href. toString ( ) ;
const re = eval ( '/(' + paramName+ '=)([^&]*)/gi' ) ;
location. href = oUrl. replace ( re, paramName+ '=' + replaceWith) ;
return location. href;
}
(5)删除URL中指定参数
export const funcUrlDel = ( name ) => {
const baseUrl = location. origin + location. pathname + "?" ;
const query = location. search. substr ( 1 ) ;
if ( query. indexOf ( name) > - 1 ) {
const obj = { } ;
const arr = query. split ( "&" ) ;
for ( let i = 0 ; i < arr. length; i++ ) {
arr[ i] = arr[ i] . split ( "=" ) ;
obj[ arr[ i] [ 0 ] ] = arr[ i] [ 1 ] ;
}
delete obj[ name] ;
return baseUrl + JSON . stringify ( obj) . replace ( / [\"\{\}] / g , "" ) . replace ( / \: / g , "=" ) . replace ( / \, / g , "&" ) ;
}
}
9. 设备判断
(1)判断是移动还是PC设备
export const isMobile = ( ) => {
if ( ( navigator. userAgent. match ( / (iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone) / i ) ) ) {
return 'mobile' ;
}
return 'desktop' ;
}
(2)判断是否是苹果还是安卓移动设备
export const isAppleMobileDevice = ( ) => {
let reg = / iphone|ipod|ipad|Macintosh / i ;
return reg. test ( navigator. userAgent. toLowerCase ( ) ) ;
}
(3)判断是否是安卓移动设备
export const isAndroidMobileDevice = ( ) => {
return / android / i . test ( navigator. userAgent. toLowerCase ( ) ) ;
}
(4)判断是Windows还是Mac系统
export const osType = ( ) => {
const agent = navigator. userAgent. toLowerCase ( ) ;
const isMac = / macintosh|mac os x / i . test ( navigator. userAgent) ;
const isWindows = agent. indexOf ( "win64" ) >= 0 || agent. indexOf ( "wow64" ) >= 0 || agent. indexOf ( "win32" ) >= 0 || agent. indexOf ( "wow32" ) >= 0 ;
if ( isWindows) {
return "windows" ;
}
if ( isMac) {
return "mac" ;
}
}
(5)判断是否是微信/QQ内置浏览器
export const broswer = ( ) => {
const ua = navigator. userAgent. toLowerCase ( ) ;
if ( ua. match ( / MicroMessenger / i ) == "micromessenger" ) {
return "weixin" ;
} else if ( ua. match ( / QQ / i ) == "qq" ) {
return "QQ" ;
}
return false ;
}
(6)浏览器型号和版本
export const getExplorerInfo = ( ) => {
let t = navigator. userAgent. toLowerCase ( ) ;
return 0 <= t. indexOf ( "msie" ) ? {
type: "IE" ,
version: Number ( t. match ( / msie ([\d]+) / ) [ 1 ] )
} : ! ! t. match ( / trident\/.+?rv:(([\d.]+)) / ) ? {
type: "IE" ,
version: 11
} : 0 <= t. indexOf ( "edge" ) ? {
type: "Edge" ,
version: Number ( t. match ( / edge\/([\d]+) / ) [ 1 ] )
} : 0 <= t. indexOf ( "firefox" ) ? {
type: "Firefox" ,
version: Number ( t. match ( / firefox\/([\d]+) / ) [ 1 ] )
} : 0 <= t. indexOf ( "chrome" ) ? {
type: "Chrome" ,
version: Number ( t. match ( / chrome\/([\d]+) / ) [ 1 ] )
} : 0 <= t. indexOf ( "opera" ) ? {
type: "Opera" ,
version: Number ( t. match ( / opera.([\d]+) / ) [ 1 ] )
} : 0 <= t. indexOf ( "Safari" ) ? {
type: "Safari" ,
version: Number ( t. match ( / version\/([\d]+) / ) [ 1 ] )
} : {
type: t,
version: - 1
}
}
export function getBrowserType ( ) {
var userAgent = navigator. userAgent;
var isOpera = userAgent. indexOf ( "Opera" ) > - 1 ;
var isIE = userAgent. indexOf ( "compatible" ) > - 1 &&
userAgent. indexOf ( "MSIE" ) > - 1 && ! isOpera;
var isEdge = userAgent. indexOf ( "Edge" ) > - 1 ;
var isFF = userAgent. indexOf ( "Firefox" ) > - 1 ;
var isSafari = userAgent. indexOf ( "Safari" ) > - 1 &&
userAgent. indexOf ( "Chrome" ) == - 1 ;
var isChrome = userAgent. indexOf ( "Chrome" ) > - 1 &&
userAgent. indexOf ( "Safari" ) > - 1 ;
if ( isIE) {
var reIE = new RegExp ( "MSIE (\\d+\\.\\d+);" ) ;
reIE. test ( userAgent) ;
var fIEVersion = parseFloat ( RegExp[ "$1" ] ) ;
if ( fIEVersion == 7 ) {
return "IE7" ;
} else if ( fIEVersion == 8 ) {
return "IE8" ;
} else if ( fIEVersion == 9 ) {
return "IE9" ;
} else if ( fIEVersion == 10 ) {
return "IE10" ;
} else if ( fIEVersion == 11 ) {
return "IE11" ;
} else {
return "0" ;
}
return "IE" ;
}
if ( isOpera) {
return "Opera" ;
}
if ( isEdge) {
return "Edge" ;
}
if ( isFF) {
return "FF" ;
}
if ( isSafari) {
return "Safari" ;
}
if ( isChrome) {
return "Chrome" ;
}
}
10. 浏览器操作
(1)滚动到页面顶部
export const scrollToTop = ( ) => {
const height = document. documentElement. scrollTop || document. body. scrollTop;
if ( height > 0 ) {
window. requestAnimationFrame ( scrollToTop) ;
window. scrollTo ( 0 , height - height / 8 ) ;
}
}
(2)滚动到页面底部
export const scrollToBottom = ( ) => {
window. scrollTo ( 0 , document. documentElement. clientHeight) ;
}
(3)滚动到指定元素区域
export const smoothScroll = ( element ) => {
document. querySelector ( element) . scrollIntoView ( {
behavior: 'smooth'
} ) ;
} ;
(4)获取可视窗口高度
export const getClientHeight = ( ) => {
let clientHeight = 0 ;
if ( document. body. clientHeight && document. documentElement. clientHeight) {
clientHeight = ( document. body. clientHeight < document. documentElement. clientHeight) ? document. body. clientHeight : document. documentElement. clientHeight;
}
else {
clientHeight = ( document. body. clientHeight > document. documentElement. clientHeight) ? document. body. clientHeight : document. documentElement. clientHeight;
}
return clientHeight;
}
(5)获取可视窗口宽度
export const getPageViewWidth = ( ) => {
return ( document. compatMode == "BackCompat" ? document. body : document. documentElement) . clientWidth;
}
(6)打开浏览器全屏
export const toFullScreen = ( ) => {
let element = document. body;
if ( element. requestFullscreen) {
element. requestFullscreen ( )
} else if ( element. mozRequestFullScreen) {
element. mozRequestFullScreen ( )
} else if ( element. msRequestFullscreen) {
element. msRequestFullscreen ( )
} else if ( element. webkitRequestFullscreen) {
element. webkitRequestFullScreen ( )
}
}
(7)退出浏览器全屏
export const exitFullscreen = ( ) => {
if ( document. exitFullscreen) {
document. exitFullscreen ( )
} else if ( document. msExitFullscreen) {
document. msExitFullscreen ( )
} else if ( document. mozCancelFullScreen) {
document. mozCancelFullScreen ( )
} else if ( document. webkitExitFullscreen) {
document. webkitExitFullscreen ( )
}
}
11. 时间操作
export const nowTime = ( ) => {
const now = new Date ( ) ;
const year = now. getFullYear ( ) ;
const month = now. getMonth ( ) ;
const date = now. getDate ( ) >= 10 ? now. getDate ( ) : ( '0' + now. getDate ( ) ) ;
const hour = now. getHours ( ) >= 10 ? now. getHours ( ) : ( '0' + now. getHours ( ) ) ;
const miu = now. getMinutes ( ) >= 10 ? now. getMinutes ( ) : ( '0' + now. getMinutes ( ) ) ;
const sec = now. getSeconds ( ) >= 10 ? now. getSeconds ( ) : ( '0' + now. getSeconds ( ) ) ;
return + year + "年" + ( month + 1 ) + "月" + date + "日 " + hour + ":" + miu + ":" + sec;
}
(2)格式化时间
export const dateFormater = ( formater, time ) => {
let date = time ? new Date ( time) : new Date ( ) ,
Y = date. getFullYear ( ) + '' ,
M = date. getMonth ( ) + 1 ,
D = date. getDate ( ) ,
H = date. getHours ( ) ,
m = date. getMinutes ( ) ,
s = date. getSeconds ( ) ;
return formater. replace ( / YYYY|yyyy / g , Y )
. replace ( / YY|yy / g , Y . substr ( 2 , 2 ) )
. replace ( / MM / g , ( M < 10 ? '0' : '' ) + M )
. replace ( / DD / g , ( D < 10 ? '0' : '' ) + D )
. replace ( / HH|hh / g , ( H < 10 ? '0' : '' ) + H )
. replace ( / mm / g , ( m< 10 ? '0' : '' ) + m)
. replace ( / ss / g , ( s< 10 ? '0' : '' ) + s)
}
12. JavaScript操作
(1)阻止冒泡事件
export const stopPropagation = ( e ) => {
e = e || window. event;
if ( e. stopPropagation) {
e. stopPropagation ( ) ;
} else {
e. cancelBubble = true ;
}
}
(2)防抖函数
export const debounce = ( fn, wait ) => {
let timer = null ;
return function ( ) {
let context = this ,
args = arguments;
if ( timer) {
clearTimeout ( timer) ;
timer = null ;
}
timer = setTimeout ( ( ) => {
fn . apply ( context, args) ;
} , wait) ;
} ;
}
(3)节流函数
export const throttle = ( fn, delay ) => {
let curTime = Date. now ( ) ;
return function ( ) {
let context = this ,
args = arguments,
nowTime = Date. now ( ) ;
if ( nowTime - curTime >= delay) {
curTime = Date. now ( ) ;
return fn . apply ( context, args) ;
}
} ;
}
(4)数据类型判断
export const getType = ( value ) => {
if ( value === null ) {
return value + "" ;
}
if ( typeof value === "object" ) {
let valueClass = Object . prototype. toString . call ( value) ,
type = valueClass. split ( " " ) [ 1 ] . split ( "" ) ;
type. pop ( ) ;
return type. join ( "" ) . toLowerCase ( ) ;
} else {
return typeof value;
}
}
(5)对象深拷贝
export const deepClone = ( obj, hash = new WeakMap ( ) ) => {
if ( obj instanceof Date ) {
return new Date ( obj) ;
}
if ( obj instanceof RegExp ) {
return new RegExp ( obj) ;
}
if ( hash. has ( obj) ) {
return hash. get ( obj) ;
}
let allDesc = Object. getOwnPropertyDescriptors ( obj) ;
let cloneObj = Object. create ( Object. getPrototypeOf ( obj) , allDesc)
hash. set ( obj, cloneObj)
for ( let key of Reflect. ownKeys ( obj) ) {
if ( typeof obj[ key] === 'object' && obj[ key] !== null ) {
cloneObj[ key] = deepClone ( obj[ key] , hash) ;
} else {
cloneObj[ key] = obj[ key] ;
}
}
return cloneObj
}
(6)其他相关
export function micrometerLevel ( str ) {
str = typeof str === 'number' ? String ( str) : str;
if ( ! str || str == '--' || String ( str) . includes ( 'NaN' ) ) {
return '--'
}
let strArr = [ ]
if ( str. includes ( '.' ) ) {
strArr = str. split ( '.' ) ;
} else {
strArr = [ str, '00' ] ;
}
return strArr[ 0 ]
. split ( '' )
. reverse ( )
. join ( '' )
. replace ( / \d{1,3} / g , str => str + ',' )
. replace ( / ,$ / , '' )
. split ( '' )
. reverse ( ) . join ( '' )
+ '.'
+ strArr[ 1 ] ;
}
export function toFixZero ( moneyStr ) {
moneyStr = typeof moneyStr == 'number' ? moneyStr. toString ( ) : moneyStr
let toZero
if ( moneyStr. split ( '.' ) [ 1 ] ) {
if ( moneyStr. split ( '.' ) [ 1 ] . length < 3 ) {
toZero = Number. parseFloat ( moneyStr) . toFixed ( 2 ) ;
} else {
toZero = Number. parseFloat ( moneyStr. substring ( 0 , moneyStr. indexOf ( '.' ) + 3 ) ) . toFixed ( 2 ) ;
}
} else {
toZero = Number. parseFloat ( moneyStr) . toFixed ( 2 ) ;
}
return toZero
}
export function accountSplit ( str, splitNumber, insert ) {
if ( ! str) {
return '--'
}
let _strArr = [ ]
for ( let i = 0 ; i < str. length; i += splitNumber) {
_strArr. push ( str. slice ( i, i + splitNumber) )
}
return _strArr. join ( insert)
}
export function parseTime ( time, cFormat ) {
if ( arguments. length === 0 ) {
return null
}
const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
let date
if ( typeof time === 'object' ) {
date = time
} else {
if ( ( typeof time === 'string' ) ) {
if ( ( / ^[0-9]+$ / . test ( time) ) ) {
time = parseInt ( time)
} else {
time = time. replace ( new RegExp ( / - / gm ) , '/' )
}
}
if ( ( typeof time === 'number' ) && ( time. toString ( ) . length === 10 ) ) {
time = time * 1000
}
date = new Date ( time)
}
const formatObj = {
y: date. getFullYear ( ) ,
m: date. getMonth ( ) + 1 ,
d: date. getDate ( ) ,
h: date. getHours ( ) ,
i: date. getMinutes ( ) ,
s: date. getSeconds ( ) ,
a: date. getDay ( )
}
const timeStr = format. replace ( / {([ymdhisa])+} / g , ( result, key ) => {
const value = formatObj[ key]
if ( key === 'a' ) { return [ '日' , '一' , '二' , '三' , '四' , '五' , '六' ] [ value] }
return value. toString ( ) . padStart ( 2 , '0' )
} )
return timeStr
}
Date . prototype. pattern = function ( fmt ) {
let o = {
"M+" : this . getMonth ( ) + 1 ,
"d+" : this . getDate ( ) ,
"h+" : this . getHours ( ) % 12 == 0 ? 12 : this . getHours ( ) % 12 ,
"H+" : this . getHours ( ) ,
"m+" : this . getMinutes ( ) ,
"s+" : this . getSeconds ( ) ,
"q+" : Math. floor ( ( this . getMonth ( ) + 3 ) / 3 ) ,
"S" : this . getMilliseconds ( )
} ;
let week = {
"0" : "天" ,
"1" : "一" ,
"2" : "二" ,
"3" : "三" ,
"4" : "四" ,
"5" : "五" ,
"6" : "六"
} ;
if ( / (y+) / . test ( fmt) ) {
fmt = fmt. replace ( RegExp. $1 , ( this . getFullYear ( ) + "" ) . substr ( 4 - RegExp. $1. length) ) ;
}
if ( / (E+) / . test ( fmt) ) {
fmt = fmt. replace ( RegExp. $1 , ( ( RegExp. $1. length > 1 ) ? ( RegExp. $1. length > 2 ? "星期" :
"周" ) : "" ) + week[ this . getDay ( ) + "" ] ) ;
}
for ( var k in o) {
if ( new RegExp ( "(" + k + ")" ) . test ( fmt) ) {
fmt = fmt. replace ( RegExp. $1 , ( RegExp. $1. length == 1 ) ? ( o[ k] ) : ( ( "00" + o[ k] ) . substr ( ( "" + o[ k] )
. length) ) ) ;
}
}
return fmt;
}
export default ( stamp, pattern = 'yyyy-MM-dd hh:mm:ss.S' ) => {
return stamp ? new Date ( parseInt ( stamp) ) . pattern ( pattern) : new Date ( ) . pattern ( pattern) ;
}
export function formatTime ( time, option ) {
if ( ( '' + time) . length === 10 ) {
time = parseInt ( time) * 1000
} else {
time = + time
}
const d = new Date ( time)
const now = Date. now ( )
const diff = ( now - d) / 1000
if ( diff < 30 ) {
return '刚刚'
} else if ( diff < 3600 ) {
return Math. ceil ( diff / 60 ) + '分钟前'
} else if ( diff < 3600 * 24 ) {
return Math. ceil ( diff / 3600 ) + '小时前'
} else if ( diff < 3600 * 24 * 2 ) {
return '1天前'
}
if ( option) {
return parseTime ( time, option)
} else {
return (
d. getMonth ( ) + 1 + '月' +
d. getDate ( ) + '日' +
d. getHours ( ) + '时' +
d. getMinutes ( ) + '分'
)
}
}
export function getQueryObject ( url ) {
url = url == null ? window. location. href : url
const search = url. substring ( url. lastIndexOf ( '?' ) + 1 )
const obj = { }
const reg = / ([^?&=]+)=([^?&=]*) / g
search. replace ( reg, ( rs, $1 , $2 ) => {
const name = decodeURIComponent ( $1 )
let val = decodeURIComponent ( $2 )
val = String ( val)
obj[ name] = val
return rs
} )
return obj
}
export function byteLength ( str ) {
let s = str. length
for ( var i = str. length - 1 ; i >= 0 ; i-- ) {
const code = str. charCodeAt ( i)
if ( code > 0x7f && code <= 0x7ff ) s++
else if ( code > 0x7ff && code <= 0xffff ) s += 2
if ( code >= 0xDC00 && code <= 0xDFFF ) i--
}
return s
}
export function cleanArray ( actual ) {
const newArray = [ ]
for ( let i = 0 ; i < actual. length; i++ ) {
if ( actual[ i] ) {
newArray. push ( actual[ i] )
}
}
return newArray
}
export function param ( json ) {
if ( ! json) return ''
return cleanArray (
Object. keys ( json) . map ( key => {
if ( json[ key] === undefined ) return ''
return encodeURIComponent ( key) + '=' + encodeURIComponent ( json[ key] )
} )
) . join ( '&' )
}
export function param2Obj ( url ) {
const search = url. split ( '?' ) [ 1 ]
if ( ! search) {
return { }
}
return JSON . parse (
'{"' +
decodeURIComponent ( search)
. replace ( / " / g , '\\"' )
. replace ( / & / g , '","' )
. replace ( / = / g , '":"' )
. replace ( / \+ / g , ' ' ) +
'"}'
)
}
export function html2Text ( val ) {
const div = document. createElement ( 'div' )
div. innerHTML = val
return div. textContent || div. innerText
}
export function objectMerge ( target, source ) {
if ( typeof target !== 'object' ) {
target = { }
}
if ( Array. isArray ( source) ) {
return source. slice ( )
}
Object. keys ( source) . forEach ( property => {
const sourceProperty = source[ property]
if ( typeof sourceProperty === 'object' ) {
target[ property] = objectMerge ( target[ property] , sourceProperty)
} else {
target[ property] = sourceProperty
}
} )
return target
}
export function toggleClass ( element, className ) {
if ( ! element || ! className) {
return
}
let classString = element. className
const nameIndex = classString. indexOf ( className)
if ( nameIndex === - 1 ) {
classString += '' + className
} else {
classString =
classString. substr ( 0 , nameIndex) +
classString. substr ( nameIndex + className. length)
}
element. className = classString
}
export function getTime ( type ) {
if ( type === 'start' ) {
return new Date ( ) . getTime ( ) - 3600 * 1000 * 24 * 90
} else {
return new Date ( new Date ( ) . toDateString ( ) )
}
}
export function debounce ( func, wait, immediate ) {
let timeout, args, context, timestamp, result
const later = function ( ) {
const last = + new Date ( ) - timestamp
if ( last < wait && last > 0 ) {
timeout = setTimeout ( later, wait - last)
} else {
timeout = null
if ( ! immediate) {
result = func . apply ( context, args)
if ( ! timeout) context = args = null
}
}
}
return function ( ... args) {
context = this
timestamp = + new Date ( )
const callNow = immediate && ! timeout
if ( ! timeout) timeout = setTimeout ( later, wait)
if ( callNow) {
result = func . apply ( context, args)
context = args = null
}
return result
}
}
export function deepClone ( source ) {
if ( ! source && typeof source !== 'object' ) {
throw new Error ( 'error arguments' , 'deepClone' )
}
const targetObj = source. constructor === Array ? [ ] : { }
Object. keys ( source) . forEach ( keys => {
if ( source[ keys] && typeof source[ keys] === 'object' ) {
targetObj[ keys] = deepClone ( source[ keys] )
} else {
targetObj[ keys] = source[ keys]
}
} )
return targetObj
}
export function uniqueArr ( arr ) {
return Array. from ( new Set ( arr) )
}
export function createUniqueString ( ) {
const timestamp = + new Date ( ) + ''
const randomNum = parseInt ( ( 1 + Math. random ( ) ) * 65536 ) + ''
return ( + ( randomNum + timestamp) ) . toString ( 32 )
}
export function hasClass ( ele, cls ) {
return ! ! ele. className. match ( new RegExp ( '(\\s|^)' + cls + '(\\s|$)' ) )
}
export function addClass ( ele, cls ) {
if ( ! hasClass ( ele, cls) ) ele. className += ' ' + cls
}
export function removeClass ( ele, cls ) {
if ( hasClass ( ele, cls) ) {
const reg = new RegExp ( '(\\s|^)' + cls + '(\\s|$)' )
ele. className = ele. className. replace ( reg, ' ' )
}
}