工具函数篇
表单序列化
export const serialize = data => { let list = [] Object.keys(data).forEach(ele => { list.push(${ele}=${data[ele]}) }) return list.join('&') }
获取对象的类型
export const getObjType = obj => { var toString = Object.prototype.toString var map = { '[object Boolean]': 'boolean', '[object Number]': 'number', '[object String]': 'string', '[object Function]': 'function', '[object Array]': 'array', '[object Date]': 'date', '[object RegExp]': 'regExp', '[object Undefined]': 'undefined', '[object Null]': 'null', '[object Object]': 'object' } if (obj instanceof Element) { return 'element' } return map[toString.call(obj)] }
对象深拷贝
export const deepClone = data => { var type = getObjType(data) var obj if (type === 'array') { obj = [] } else if (type === 'object') { obj = {} } else { // 不再具有下一层次 return data } if (type === 'array') { for (var i = 0, len = data.length; i < len; i++) { obj.push(deepClone(data[i])) } } else if (type === 'object') { for (var key in data) { obj[key] = deepClone(data[key]) } } return obj }
判断路由是否相等
export const diff = (obj1, obj2) => { delete obj1.close var o1 = obj1 instanceof Object var o2 = obj2 instanceof Object if (!o1 || !o2) { / 判断不是对象 / return obj1 === obj2 } if (Object.keys(obj1).length !== Object.keys(obj2).length) { return false // Object.keys() 返回一个由对象的自身可枚举属性(key值)组成的数组,例如:数组返回下标:let arr = ["a", "b", "c"];console.log(Object.keys(arr))->0,1,2; } for (var attr in obj1) { var t1 = obj1[attr] instanceof Object var t2 = obj2[attr] instanceof Object if (t1 && t2) { return diff(obj1[attr], obj2[attr]) } else if (obj1[attr] !== obj2[attr]) { return false } } return true }
递归寻找子类的父类
export const findParent = (menu, id) => { for (let i = 0; i < menu.length; i++) { if (menu[i].children.length != 0) { for (let j = 0; j < menu[i].children.length; j++) { if (menu[i].children[j].id == id) { return menu[i] } else { if (menu[i].children[j].children.length != 0) { return findParent(menu[i].children[j].children, id) } } } } } }
动态插入css
export const loadStyle = url => { const link = document.createElement('link') link.type = 'text/css' link.rel = 'stylesheet' link.href = url const head = document.getElementsByTagName('head')[0] head.appendChild(link) }
根据字典的value查找对应的index
export const findArray = (dic, value) => { for (let i = 0; i < dic.length; i++) { if (dic[i].value == value) { return i } } return -1 }
根据字典的value显示label
export const findByvalue = (dic, value) => { let result = '' if (validatenull(dic)) return value if (typeof (value) === 'string' || typeof (value) === 'number' || typeof (value) === 'boolean') { let index = 0 index = findArray(dic, value) if (index != -1) { result = dic[index].label } else { result = value } } else if (value instanceof Array) { result = [] let index = 0 value.forEach(ele => { index = findArray(dic, ele) if (index != -1) { result.push(dic[index].label) } else { result.push(value) } }) result = result.toString() } return result }
生成随机len位数字
export const randomLenNum = (len, date) => { let random = '' random = Math.ceil(Math.random() * 100000000000000).toString().substr(0, len || 4) if (date) random = random + Date.now() return random }
解决ie9不兼容placeholder问题
export function compatiblePlaceholder() { if (!('placeholder' in document.createElement('input'))) { // 将返回的nodeList对象转为数组 var nodes = Array.prototype.slice.call(document.querySelectorAll('[placeholder]')) nodes.forEach(function (item, index) { if (item.nextElementSibling) { } else { item.addEventListener('focus', function () { this.nextSibling.style.display = 'none' }) item.addEventListener('blur', function () { if (!this.value) { this.style.display = 'none' this.nextSibling.style.display = 'inline' } }) var cloneNode = item.cloneNode() // 如果[type='password']类型,则转为text if (cloneNode.getAttribute('type').toLowerCase() === 'password') { cloneNode.setAttribute('type', 'text') } cloneNode.setAttribute('value', cloneNode.getAttribute('placeholder')) cloneNode.style.display = 'none' item.insertAdjacentHTML('afterend', cloneNode.outerHTML) item.nextSibling.addEventListener('focus', function () { this.style.display = 'none' this.previousSibling.style.display = 'inline' this.previousSibling.focus() }) if (!item.value) { item.style.display = 'none' item.nextSibling.style.display = 'inline' } } }) } }
精度丢失转换(乘法)
export function accMul(arg1, arg2) { let m = 0, s1 = arg1.toString(), s2 = arg2.toString(); try { m += s1.split(".")[1].length } catch (e) { } try { m += s2.split(".")[1].length } catch (e) { } return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m) }
节流函数
/** • 节流函数,在一段时间内,回调函数只执行一次 • @param {Function} fun 需要节流的函数 • @param {number} delay 节流的时间,单位为毫秒 */ export function throttle(fun, delay) { let valid = true; return function() { let context = this; let args = arguments; if (!valid) { return; } valid = false; setTimeout(() => { fn.apply(context, args); valid = true; }, delay); } }
防抖函数
/** *防抖函数,多次触发事件后,事件处理函数只执行一次,并且是在触发操作结束时执行 *@param fn 事件触发的操作 *@param delay 多少毫秒内连续触发事件,不会执行 *@returns {Function} */ function debounce(fn, delay){ let timer = null; //借助闭包 return function(){ let context = this, args = arguments; timer && clearTimeout(timer); timer = setTimeout(function(){ fn.apply(context, args); },delay); } }
计算时间和当前时间的差值
export const spaceTime = function (atime) { atime = atime.replace(/-/g, '/'); //IE出现兼容问题,带“-”格式的时间无法被new Date()转成时间格式,返回NaN. let byTime = [365 24 60 60 1000, 24 60 60 1000, 60 60 1000, 60 1000, 1000]; let unit = ["年", "天", "小时", "分钟", "秒钟"]; var ct = new Date().getTime() - new Date(atime).getTime(); if (ct <= 1000) { // return "时间数据出错!" return "刚刚" } var sb = []; for (var i = 0; i < byTime.length; i++) { if (ct < byTime[i]) { continue; } var temp = Math.floor(ct / byTime[i]); ct = ct % byTime[i]; if (temp > 0) { sb.push(temp + unit[i]); }
/*一下控制最多输出几个时间单位: 一个时间单位如:N分钟前 两个时间单位如:M分钟N秒前 三个时间单位如:M年N分钟X秒前 以此类推 */ if (sb.length >= 1) { break; } } return (sb.join("") + "前"); }
获取当前年月
export const getNowFormatDate = function() { var date = new Date(); var seperator1 = "-"; var year = date.getFullYear(); var month = date.getMonth() + 1; var strDate = date.getDate(); if (month >= 1 && month <= 9) { month = "0" + month; } if (strDate >= 0 && strDate <= 9) { strDate = "0" + strDate; } var currentdate = year + seperator1 + month; return currentdate; }
获取指定时间年月日
export const getFormatDate = function(data) { var date = new Date(data); var seperator1 = "-"; var year = date.getFullYear(); var month = date.getMonth() + 1; var strDate = date.getDate(); if (month >= 1 && month <= 9) { month = "0" + month; } if (strDate >= 0 && strDate <= 9) { strDate = "0" + strDate; } var currentdate = year + seperator1 + month+strDate; return currentdate; }