/** * 10000 => "10,000" * @param {number}num */ exportfunctiontoThousandFilter(num) { let targetNum = (num || 0).toString() if (targetNum.includes('.')) { let arr = num.split('.') return arr[0].replace(/^-?\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ',')) + '.' + arr[1] } else { return targetNum.replace(/^-?\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ',')) } }
过滤成版本号
/** * version filter * 50397188 => 3.1.0.4 * @param {number}versions */ exportfunctionversionFilter(versions) { let v0 = (versions & 0xff000000) >> 24 let v1 = (versions & 0xff0000) >> 16 let v2 = (versions & 0xff00) >> 8 let v3 = versions & 0xff return`${v0}.${v1}.${v2}.${v3}` }
首字母大写
/** * Upper case first char * @param {String}string */ exportfunctionuppercaseFirst(string) { return string.charAt(0).toUpperCase() + string.slice(1) }
class骚操作
/** * Check if an element has a class * @param {HTMLElement}elm * @param {string}cls * @returns {boolean} */ exportfunctionhasClass(ele, cls) { return !!ele.className.match(newRegExp('(\\s|^)' + cls + '(\\s|$)')) }
/** * Add class to element * @param {HTMLElement}elm * @param {string}cls */ exportfunctionaddClass(ele, cls) { if (!hasClass(ele, cls)) ele.className += ' ' + cls }
/** * Remove class from element * @param {HTMLElement}elm * @param {string}cls */ exportfunctionremoveClass(ele, cls) { if (hasClass(ele, cls)) { const reg = newRegExp('(\\s|^)' + cls + '(\\s|$)') ele.className = ele.className.replace(reg, ' ') } }
文本复制功能
const copyTxt = function(text, fn) { // 复制功能 if (typeofdocument.execCommand !== 'function') { console.log('复制失败,请长按复制') return } var dom = document.createElement('textarea') dom.value = text dom.setAttribute('style', 'display: block;width: 1px;height: 1px;') document.body.appendChild(dom) dom.select() var result = document.execCommand('copy') document.body.removeChild(dom) if (result) { console.log('复制成功') typeof fn === 'function' && fn() return } if (typeofdocument.createRange !== 'function') { console.log('复制失败,请长按复制') return } var range = document.createRange() var div = document.createElement('div') div.innerhtml = text div.setAttribute('style', 'height: 1px;fontSize: 1px;overflow: hidden;') document.body.appendChild(div) range.selectNode(div) var selection = window.getSelection() console.log(selection) if (selection.rangeCount > 0) { selection.removeAllRanges() } selection.addRange(range) document.execCommand('copy') typeof fn === 'function' && fn() console.log('复制成功') }
判断是否是一个数组
exportconst castArray = value => (Array.isArray(value) ? value : [value])
// Or exportconst castArray = arr=>Object.prototype.toString.call(arr) === '[object Array]'
exportconst isPC = function() { // 是否为PC端 let userAgentInfo = navigator.userAgent let Agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod'] let flag = true for (let v = 0; v < Agents.length; v++) { if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = false break } } return flag }
判断是否为微信
exportconst isWx = () => { // 判断是否为微信 var ua = window.navigator.userAgent.toLowerCase() if (ua.match(/MicroMessenger/i) === 'micromessenger') { returntrue } returnfalse }
设备判断:android、ios、web
exportconst isDevice = function() { // 判断是android还是ios还是web var ua = navigator.userAgent.toLowerCase() if (ua.match(/iPhone\sOS/i) === 'iphone os' || ua.match(/iPad/i) === 'ipad') { // ios return'iOS' } if (ua.match(/Android/i) === 'android') { return'Android' } return'Web' }
// for example let data = { id: 1, title: '12345', name: '男'} omit(data, ['id']) // data ---> {title: 'xxx', name: '男'}
深拷贝
/** * This is just a simple version of deep copy * Has a lot of edge cases bug * If you want to use a perfect deep copy, use lodash's _.cloneDeep * @param {Object}source * @returns {Object} */ exportfunctiondeepClone(source) { if (!source && typeof source !== 'object') { thrownewError('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 }
函数防抖
exportfunctiondebounce(func, wait, immediate) { let timeout, args, context, timestamp, result const later = function() { // 据上一次触发时间间隔 const last = +newDate() - timestamp
// 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait if (last < wait && last > 0) { timeout = setTimeout(later, wait - last) } else { timeout = null // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用 if (!immediate) { result = func.apply(context, args) if (!timeout) context = args = null } } } returnfunction(...args) { context = this timestamp = +newDate() const callNow = immediate && !timeout // 如果延时不存在,重新设定延时 if (!timeout) timeout = setTimeout(later, wait) if (callNow) { result = func.apply(context, args) context = args = null } return result } }
函数节流
/** * @param {Function}func 目标函数 * @param {Number}wait 延迟执行毫秒数 * @param {Number}type type 1 表时间戳版,2 表定时器版 */ exportfunction(func, wait ,type) { if(type===1){ let previous = 0; }elseif(type===2){ let timeout; } returnfunction() { let context = this; let args = arguments; if(type===1){ let now = Date.now(); if (now - previous > wait) { func.apply(context, args); previous = now; } }elseif(type===2){ if (!timeout) { timeout = setTimeout(() => { timeout = null; func.apply(context, args) }, wait) } } } }