工具类
Posted jscai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了工具类相关的知识,希望对你有一定的参考价值。
/** * 数组相关工具类 */ class ArrayClazz { /** * 提取对象数组中的某一个属性名,重新组成一个新的数组 * @param obj 对象数组 * @param field 属性名称 * @param needSpace true,往数组第一个位置插入空值 * @returns {Array} 新数组 * 例子: obj[{name:a,age:18},{name:b},{name:‘c‘,age:20}] * objectToArray(obj,‘name‘,true) 返回 [‘‘,‘a‘,‘b‘,‘c‘] * objectToArray(obj,‘name‘,false) 返回 [‘a‘,‘b‘,‘c‘]//默认 */ objectToArray(obj, field, needSpace) { let arr = []; obj = obj || {}; needSpace = needSpace || false; if (needSpace) { arr.push(‘‘); } for (let i = 0; i < obj.length; i++) { if (obj[i][field] !== undefined) { arr.push(obj[i][field]); } } return arr; } /** * 获取数组最大值 * 需要数组内都是可以转化为数值的 * @param arr * @returns {number} 最大值 */ max(arr) { return Math.max.apply(Math, arr); } /** * 获取数组最小值 * 需要数组内都是可以转化为数值的 * @param arr * @returns {number} 最小值 */ min(arr) { return Math.min.apply(Math, arr); } /** * 平均值 * @returns {number} 平均值 */ avg(arr) { return this.sum(arr) / arr.length; } /** * 求和 * @returns {number} 和 */ sum(arr) { return arr.reduce((pre, cur) => { return pre + cur; }); } /** * 判断一个元素是否在数组中 * @param arr 数组 * @param val 元素 * @returns {boolean} */ contains(arr, val) { return arr.indexOf(val) != -1; } /** * @param {arr} 数组 * @param {type} 1:从小到大 2:从大到小 3:随机 * @return {Array} */ sort(arr, type = 1) { return arr.sort((a, b) => { switch (type) { case 1: return a - b; case 2: return b - a; case 3: return Math.random() - 0.5; default: return arr; } }); } /** * 删除数组中的某个元素 * @param arr 数组 * @param ele 元素 * @returns {*} 新数组 */ remove(arr, ele) { var index = arr.indexOf(ele); if (index > -1) { arr.splice(index, 1); } return arr; } /** * 将类数组转换为数组的方法 * @param ary 类数组 * @returns {Array} 行书住 */ formArray(ary) { var arr = []; if (Array.isArray(ary)) { arr = ary; } else { arr = Array.prototype.slice.call(ary); } return arr; } /** * 数组去重复 * @param arr 数组 * returns 新数组 */ unique(arr) { if (Array.hasOwnProperty(‘from‘)) { return Array.from(new Set(arr)); } else { var n = {}, r = []; for (var i = 0; i < arr.length; i++) { if (!n[arr[i]]) { n[arr[i]] = true; r.push(arr[i]); } } return r; } // 注:上面 else 里面的排重并不能区分 2 和 ‘2‘,但能减少用indexOf带来的性能,暂时没找到替代的方法。。。 /* 正确排重 if ( Array.hasOwnProperty(‘from‘) ) { return Array.from(new Set(arr)) }else{ var r = [], NaNBol = true for(var i=0; i < arr.length; i++) { if (arr[i] !== arr[i]) { if (NaNBol && r.indexOf(arr[i]) === -1) { r.push(arr[i]) NaNBol = false } }else{ if(r.indexOf(arr[i]) === -1) r.push(arr[i]) } } return r } */ } /** * 数组去重复,作用于对象 * @param arr 数组 * @param filed 根据数组内对象的属性名来去除重复们可以是多个 * @returns {Array} */ unique2(arr = [], ...filed) { let hash = {}; arr = arr.reduce(function(item, next) { for (let i = 0; i < filed.length; i++) { hash[next[filed[i]]] ? ‘‘ : (hash[next[filed[i]]] = true && item.push(next)); } return item; }, []); return arr; } /** * 求两个数组的并集 * @param a 数组a * @param b 数组b * @returns {*} 并集数组 */ union(a, b) { var newArr = a.concat(b); return this.unique(newArr); } /** * 求两个数组的交集 * @param a a数组 * @param b b数组 * @returns {Uint8Array | any[] | Int32Array | Uint16Array | Uint32Array | Float64Array | any} */ intersect(a, b) { var _this = this; a = this.unique(a); return this.map(a, function(o) { return _this.contains(b, o) ? o : null; }); } /** * @desc 判断数组是否相等 * @param {arr1,arr2} * @return {Boolean} */ arrayEqual(arr1, arr2) { if (arr1 === arr2) return true; if (arr1.length !== arr2.length) return false; for (var i = 0; i < arr1.length; ++i) { if (arr1[i] !== arr2[i]) return false; } return true; } } /** * 字符串相关工具类 */ class StringClazz { /** * 判断字符串是否为空,可以为多个空格 * @param str * @returns {boolean} */ isEmptyOrNull(str) { return str == null || str == ‘‘; } /** * 判断字符串是否为为空,多个空格也为空 * @param str * @returns {boolean} */ isBlankOrNull(str) { return str == null || /^s*$/.test(str); } /** * 去除空格 * @param {str} * @param {type} * type: 1-所有空格 2-前后空格 3-左空格 4-右空格 * @return {String} */ trim(str, type) { type = type || 1; switch (type) { case 1: return str.replace(/s+/g, ‘‘); case 2: return str.replace(/(^s*)|(s*$)/g, ‘‘); case 3: return str.replace(/(^s*)/g, ‘‘); case 4: return str.replace(/(s*$)/g, ‘‘); default: return str; } } /** * 比较两个字符串是否相等 * @param input1 * @param input2 * @returns {boolean} */ equals(str1, str2) { return str1 === str2; } /** * 忽略大小写比较两个字符串是否相等 * @param str1 * @param str2 * @returns {boolean} */ equalsIgnoreCase(str1, str2) { return str1.toLocaleLowerCase() === str2.toLocaleLowerCase(); } /** * @param {str} * @param {type} * type: 1:首字母大写 2:首页母小写 3:大小写转换 4:全部大写 5:全部小写 * @return {String} */ changeCase(str, type) { type = type || 4; switch (type) { case 1: return str.replace(/w+/g, function(word) { return ( word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase() ); }); case 2: return str.replace(/w+/g, function(word) { return ( word.substring(0, 1).toLowerCase() + word.substring(1).toUpperCase() ); }); case 3: return str .split(‘‘) .map(function(word) { if (/[a-z]/.test(word)) { return word.toUpperCase(); } else { return word.toLowerCase(); } }) .join(‘‘); case 4: return str.toUpperCase(); case 5: return str.toLowerCase(); default: return str; } } /** * 检测密码强度 * @param str 密码字符串 */ checkPwd(str) { var Lv = 0; if (str.length < 6) { return Lv; } if (/[0-9]/.test(str)) { Lv++; } if (/[a-z]/.test(str)) { Lv++; } if (/[A-Z]/.test(str)) { Lv++; } if (/[.|-|_]/.test(str)) { Lv++; } return Lv; } /** * 过滤html代码(把<>转换) * @param str * @returns {*} */ filterTag(str) { str = str.replace(/&/gi, ‘&‘); str = str.replace(/</gi, ‘<‘); str = str.replace(/>/gi, ‘>‘); str = str.replace(‘ ‘, ‘ ‘); return str; } } /** * 日期相关工具类 */ class DateClazz { /** * 对Date的扩展,将 Date 转化为指定格式的String * 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符, * 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字) * 例子: * (new Date()).Format(‘yyyy-MM-dd hh:mm:ss.S‘) ==> 2006-07-02 08:09:04.423 * (new Date()).Format(‘yyyy-M-d h:m:s.S‘) ==> 2006-7-2 8:9:4.18 * @param date 需要格式化的时间, * @param pattern 格式化样式,默认 * @returns {*} 格式化后的字符串 * @constructor */ format(date = new Date(), pattern = ‘yyyy-MM-dd‘) { if (/(y+)/.test(pattern)) { pattern = pattern.replace( RegExp.$1, (date.getFullYear() + ‘‘).substr(4 - RegExp.$1.length) ); } let o = { ‘M+‘: date.getMonth() + 1, ‘d+‘: date.getDate(), ‘h+‘: date.getHours(), ‘m+‘: date.getMinutes(), ‘s+‘: date.getSeconds() }; for (let k in o) { if (new RegExp(`(${k})`).test(pattern)) { let str = o[k] + ‘‘; pattern = pattern.replace( RegExp.$1, RegExp.$1.length === 1 ? str : (‘00‘ + str).substr(str.length) ); } } return pattern; } /** * 将时间字符串转换成时间 * @param dateString 时间字符串 * @param pattern 格式 * @returns {*} * 字符串格式必须和pattern格式一致,否则返回null * 例子 parse(‘2018-01-19‘,‘yyyy-MM-dd‘) //Fri Jan 19 2018 00:00:00 GMT+0800 (中国标准时间) */ parse(dateString, pattern) { let matchs1 = pattern.match(/([yMdhsm])(1*)/g); let matchs2 = dateString.match(/(d)+/g); if (matchs1.length === matchs2.length) { let _date = new Date(1970, 0, 1); for (let i = 0; i < matchs1.length; i++) { let _int = parseInt(matchs2[i]); let sign = matchs1[i]; switch (sign.charAt(0)) { case ‘y‘: _date.setFullYear(_int); break; case ‘M‘: _date.setMonth(_int - 1); break; case ‘d‘: _date.setDate(_int); break; case ‘h‘: _date.setHours(_int); break; case ‘m‘: _date.setMinutes(_int); break; case ‘s‘: _date.setSeconds(_int); break; } } return _date; } return null; } /** * 获取时区名和时区值 * @param dateObj 时间对象 * @returns {{name: string, value: string}} {name: ‘GMT‘, value: ‘+0800‘} */ getZoneNameValue(dateObj) { let date = new Date(dateObj); date = new Date( Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) ); let arr = date.toString().match(/([A-Z]+)([-+]d+:?d+)/); let obj = { name: arr[1], value: arr[2] }; return obj; } /** * 返回指定长度的月份集合 * * @param {time} 时间 * @param {len} 长度 * @param {direction} 方向: 1: 前几个月; 2: 后几个月; 3:前后几个月 默认 3 * @return {Array} 数组 * * @example getMonths(‘2018-1-29‘, 6, 1) // -> [‘2018-1‘, ‘2017-12‘, ‘2017-11‘, ‘2017-10‘, ‘2017-9‘, ‘2017-8‘, ‘2017-7‘] */ getMonths(time, len, direction) { var mm = new Date(time).getMonth(), yy = new Date(time).getFullYear(), direction = isNaN(direction) ? 3 : direction, index = mm; var cutMonth = function(index) { if (index <= len && index >= -len) { return direction === 1 ? formatPre(index).concat(cutMonth(++index)) : direction === 2 ? formatNext(index).concat(cutMonth(++index)) : formatCurr(index).concat(cutMonth(++index)); } return []; }; var formatNext = function(i) { var y = Math.floor(i / 12), m = i % 12; return [yy + y + ‘-‘ + (m + 1)]; }; var formatPre = function(i) { var y = Math.ceil(i / 12), m = i % 12; m = m === 0 ? 12 : m; return [yy - y + ‘-‘ + (13 - m)]; }; var formatCurr = function(i) { var y = Math.floor(i / 12), yNext = Math.ceil(i / 12), m = i % 12, mNext = m === 0 ? 12 : m; return [yy - yNext + ‘-‘ + (13 - mNext), yy + y + ‘-‘ + (m + 1)]; }; // 数组去重 var unique = function(arr) { if (Array.hasOwnProperty(‘from‘)) { return Array.from(new Set(arr)); } else { var n = {}, r = []; for (var i = 0; i < arr.length; i++) { if (!n[arr[i]]) { n[arr[i]] = true; r.push(arr[i]); } } return r; } }; return direction !== 3 ? cutMonth(index) : unique( cutMonth(index).sort(function(t1, t2) { return new Date(t1).getTime() - new Date(t2).getTime(); }) ); } /** * 返回指定长度的天数集合 * * @param {time} 时间 * @param {len} 长度 * @param {direction} 方向: 1: 前几天; 2: 后几天; 3:前后几天 默认 3 * @return {Array} 数组 * * @example date.getDays(‘2018-1-29‘, 6) // -> [‘2018-1-26‘, ‘2018-1-27‘, ‘2018-1-28‘, ‘2018-1-29‘, ‘2018-1-30‘, ‘2018-1-31‘, ‘2018-2-1‘] */ getDays(time, len, diretion) { var tt = new Date(time); var getDay = function(day) { var t = new Date(time); t.setDate(t.getDate() + day); var m = t.getMonth() + 1; return t.getFullYear() + ‘-‘ + m + ‘-‘ + t.getDate(); }; var arr = []; if (diretion === 1) { for (var i = 1; i <= len; i++) { arr.unshift(getDay(-i)); } } else if (diretion === 2) { for (var i = 1; i <= len; i++) { arr.push(getDay(i)); } } else { for (var i = 1; i <= len; i++) { arr.unshift(getDay(-i)); } arr.push( tt.getFullYear() + ‘-‘ + (tt.getMonth() + 1) + ‘-‘ + tt.getDate() ); for (var i = 1; i <= len; i++) { arr.push(getDay(i)); } } return diretion === 1 ? arr.concat([ tt.getFullYear() + ‘-‘ + (tt.getMonth() + 1) + ‘-‘ + tt.getDate() ]) : diretion === 2 ? [ tt.getFullYear() + ‘-‘ + (tt.getMonth() + 1) + ‘-‘ + tt.getDate() ].concat(arr) : arr; } /** * @param {s} 秒数 * @return {String} 字符串 * * @example formatHMS(3610) // -> 1h0m10s */ formatHMS(s) { var str = ‘‘; if (s > 3600) { str = Math.floor(s / 3600) + ‘h‘ + Math.floor((s % 3600) / 60) + ‘m‘ + (s % 60) + ‘s‘; } else if (s > 60) { str = Math.floor(s / 60) + ‘m‘ + (s % 60) + ‘s‘; } else { str = (s % 60) + ‘s‘; } return str; } /** * 获取某月多少天 * @param time 时间字符串 ‘2018-2-5‘或者毫秒 * @returns {*} getMonthOfDay(2018-2-5‘)==>29 */ getMonthOfDay(time) { var date = new Date(time); var year = date.getFullYear(); var mouth = date.getMonth() + 1; var days; //当月份为二月时,根据闰年还是非闰年判断天数 if (mouth == 2) { days = (year % 4 == 0 && year % 100 == 0 && year % 400 == 0) || (year % 4 == 0 && year % 100 != 0) ? 29 : 28; } else if ( mouth == 1 || mouth == 3 || mouth == 5 || mouth == 7 || mouth == 8 || mouth == 10 || mouth == 12 ) { //月份为:1,3,5,7,8,10,12 时,为大月.则天数为31; days = 31; } else { //其他月份,天数为:30. days = 30; } return days; } /*获取某年有多少天*/ getYearOfDay(time) { var firstDayYear = this.getFirstDayOfYear(time); var lastDayYear = this.getLastDayOfYear(time); var numSecond = (new Date(lastDayYear).getTime() - new Date(firstDayYear).getTime()) / 1000; return Math.ceil(numSecond / (24 * 3600)); } /** * 获取某年的第一天 * @param time 时间字符串 ‘2018-2-5‘或者毫秒 * @returns {string} */ getFirstDayOfYear(time) { var year = new Date(time).getFullYear(); return year + ‘-01-01 00:00:00‘; } /** * 获取某年最后一天 * @param time 时间字符串 ‘2018-2-5‘或者毫秒 * @returns {string} */ getLastDayOfYear(time) { var year = new Date(time).getFullYear(); var dateString = year + ‘-12-01 00:00:00‘; var endDay = this.getMonthOfDay(dateString); return year + ‘-12-‘ + endDay + ‘ 23:59:59‘; } /** * 获取某个日期是当年中的第几天 * @param time 时间字符串 ‘2018-2-5‘或者毫秒 * @returns {number} */ getDayOfYear(time) { var firstDayYear = this.getFirstDayOfYear(time); var numSecond = (new Date(time).getTime() - new Date(firstDayYear).getTime()) / 1000; return Math.ceil(numSecond / (24 * 3600)); } /** * 获取某个日期在这一年的第几周 * @param time 时间字符串 ‘2018-2-5‘ 或者毫秒 * @returns {number} */ getDayOfYearWeek(time) { var numdays = this.getDayOfYear(time); return Math.ceil(numdays / 7); } } /** * 类型校验相关工具类 */ class TypeClazz { //判断对象类型 typeOf(obj) { return Object.prototype.toString.call(obj).slice(8, -1); } //是否字符串 isString(o) { return Object.prototype.toString.call(o).slice(8, -1) === ‘String‘; } //是否数字 isNumber(o) { return Object.prototype.toString.call(o).slice(8, -1) === ‘Number‘; } //是否对象 isObj(o) { return Object.prototype.toString.call(o).slice(8, -1) === ‘Object‘; } //是否数组 isArray(o) { return Object.prototype.toString.call(o).slice(8, -1) === ‘Array‘; } //是否时间 isDate(o) { return Object.prototype.toString.call(o).slice(8, -1) === ‘Date‘; } //是否boolean isBoolean(o) { return Object.prototype.toString.call(o).slice(8, -1) === ‘Boolean‘; } //是否函数 isFunction(o) { return Object.prototype.toString.call(o).slice(8, -1) === ‘Function‘; } //是否为null isNull(o) { return Object.prototype.toString.call(o).slice(8, -1) === ‘Null‘; } //是否undefined isUndefined(o) { return Object.prototype.toString.call(o).slice(8, -1) === ‘Undefined‘; } //是否为null undefined false NaN isFalse(o) { if ( !o || o === ‘null‘ || o === ‘undefined‘ || o === ‘false‘ || o === ‘NaN‘ ) { return true; } return false; } //不为null undefined false NaN isTrue(o) { return !this.isFalse(o); } //是否是ios设备 isIos() { var u = navigator.userAgent; if (u.indexOf(‘android‘) > -1 || u.indexOf(‘Linux‘) > -1) { //安卓手机 // return ‘Android‘; return false; } else if (u.indexOf(‘iPhone‘) > -1) { //苹果手机 // return ‘iPhone‘; return true; } else if (u.indexOf(‘iPad‘) > -1) { //iPad // return ‘iPad‘; return false; } else if (u.indexOf(‘Windows Phone‘) > -1) { //winphone手机 // return ‘Windows Phone‘; return false; } else { return false; } } /** * 是否是pc端 * @returns {boolean} */ isPC() { //是否为PC端 var userAgentInfo = navigator.userAgent; var Agents = [ ‘Android‘, ‘iPhone‘, ‘SymbianOS‘, ‘Windows Phone‘, ‘iPad‘, ‘iPod‘ ]; var flag = true; for (var v = 0; v < Agents.length; v++) { if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = false; break; } } return flag; } /** * 判断浏览器类型 * @returns {string} */ browserType() { var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串 var isOpera = userAgent.indexOf(‘Opera‘) > -1; //判断是否Opera浏览器 var isIE = userAgent.indexOf(‘compatible‘) > -1 && userAgent.indexOf(‘MSIE‘) > -1 && !isOpera; //判断是否IE浏览器 var isEdge = userAgent.indexOf(‘Edge‘) > -1; //判断是否IE的Edge浏览器 var isFF = userAgent.indexOf(‘Firefox‘) > -1; //判断是否Firefox浏览器 var isSafari = userAgent.indexOf(‘Safari‘) > -1 && userAgent.indexOf(‘Chrome‘) == -1; //判断是否Safari浏览器 var isChrome = userAgent.indexOf(‘Chrome‘) > -1 && userAgent.indexOf(‘Safari‘) > -1; //判断Chrome浏览器 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 ‘IE7以下‘; //IE版本过低 } if (isFF) return ‘FF‘; if (isOpera) return ‘Opera‘; if (isEdge) return ‘Edge‘; if (isSafari) return ‘Safari‘; if (isChrome) return ‘Chrome‘; } /** * @desc 是否微信内置浏览器 * @return {Boolean} */ isWeixin() { var ua = navigator.userAgent.toLowerCase(); if (ua.match(/MicroMessenger/i) == ‘micromessenger‘) { return true; } else { return false; } } /** * @desc 获取操作系统类型 * @return {String} */ mobileType() { var u = navigator.userAgent; var isAndroid = u.indexOf(‘Android‘) > -1 || u.indexOf(‘Adr‘) > -1; //android终端 var isiOS = !!u.match(/(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端 if (isAndroid) { return ‘android‘; } else if (isiOS) { return ‘iphone‘; } } /** * @desc 判断是手机系统或者pc * @return {String} */ getOs() { var sUserAgent = navigator.userAgent.toLowerCase(); var bIsIpad = sUserAgent.match(/ipad/i) == ‘ipad‘; var bIsIphoneOs = sUserAgent.match(/iphone os/i) == ‘iphone os‘; var bIsMidp = sUserAgent.match(/midp/i) == ‘midp‘; var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == ‘rv:1.2.3.4‘; var bIsUc = sUserAgent.match(/ucweb/i) == ‘ucweb‘; var bIsAndroid = sUserAgent.match(/android/i) == ‘android‘; var bIsCE = sUserAgent.match(/windows ce/i) == ‘windows ce‘; var bIsWM = sUserAgent.match(/windows mobile/i) == ‘windows mobile‘; if ( bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM ) { return ‘mobile‘; } else { return ‘web‘; } } } /** * url操作相关工具类 */ class urlClazz { // 获取地址栏参数 GetQueryString(name) { var reg = new RegExp(‘(^|&)‘ + name + ‘=([^&]*)(&|$)‘); var r = decodeURI(window.location.search.substr(1)).match(reg); if (r != null) return unescape(r[2]); return null; } /** * 根据参数名获取URL上面的参数 * @param name 参数名 * @returns {string} 参数值 * 例子: * www.baidu.com?a=3&b=4 * getUrlParamByName(‘a‘) // 3 * getUrlParamByName(‘b‘) // 4 */ getUrlParamByName(name) { var reg = new RegExp(‘(^|&)‘ + name + ‘=([^&]*)(&|$)‘, ‘i‘); var r = window.location.search.substr(1).match(reg); var context = ‘‘; if (r != null) context = r[2]; reg = null; r = null; return context == null || context == ‘‘ || context == ‘undefined‘ ? ‘‘ : context; } /** * 获取url上面的所有参数,并返回一个数组 * 例子:www.baidu.com?a=3&b=4 * ==>[a:3,b:4] * @returns {Array} */ getUrlParams() { var querystr = window.location.href.split(‘?‘), GETs = ‘‘, GET = ‘‘; if (querystr[1]) { GETs = querystr[1].split(‘&‘); GET = []; for (i = 0; i < GETs.length; i++) { tmp_arr = GETs[i].split(‘=‘); var key = tmp_arr[0]; GET[key] = tmp_arr[1]; } } return GET; } /** * 提取url链接上面的参数转化为obj对象 * @param url 需处理的url * @returns {{}} 处理后的参数链接 * 例子: * getUrlParamToObj(‘www.baidu.com?a=3&b=4‘) * ==>{a: ‘3‘, b: ‘4‘} */ getUrlParamToObj(url) { var regex = /(w+)=([^&#]*)/gim; var matchStr = null; var obj = {}; while ((matchStr = regex.exec(url)) != null) { obj[matchStr[1]] = matchStr[2]; } return obj; } /** * 将对象添加当作参数拼接到URL上面 * @param baseUrl 需要拼接的url * @param obj 参数对象 * @returns {string} 拼接后的对象 * 例子: * let obj = {a: ‘3‘, b: ‘4‘} * setObjToUrlParams(‘www.baidu.com‘, obj) * ==>www.baidu.com?a=3&b=4 */ setObjToUrlParams(baseUrl, obj) { let parameters = ‘‘; let url = ‘‘; for (let key in obj) { parameters += key + ‘=‘ + obj[key] + ‘&‘; } parameters = parameters.replace(/&$/, ‘‘); if (/?$/.test(baseUrl)) { url = baseUrl + parameters; } else { url = baseUrl.replace(//?$/, ‘?‘) + parameters; } return url; } /** * 获取全部url参数,并转换成json对象 * @param url * @returns {{}} */ getUrlAllParams(url) { var url = url ? url : window.location.href; var _pa = url.substring(url.indexOf(‘?‘) + 1), _arrS = _pa.split(‘&‘), _rs = {}; for (var i = 0, _len = _arrS.length; i < _len; i++) { var pos = _arrS[i].indexOf(‘=‘); if (pos == -1) { continue; } var name = _arrS[i].substring(0, pos), value = window.decodeURIComponent(_arrS[i].substring(pos + 1)); _rs[name] = value; } return _rs; } /** * 删除url指定参数,返回url * @param url * @param name 参数名 * @returns {*} */ delParamsUrl(url, name) { var baseUrl = url.split(‘?‘)[0] + ‘?‘; var query = url.split(‘?‘)[1]; if (query.indexOf(name) > -1) { var obj = {}; var arr = query.split(‘&‘); for (var i = 0; i < arr.length; i++) { arr[i] = arr[i].split(‘=‘); obj[arr[i][0]] = arr[i][1]; } delete obj[name]; var url = baseUrl + JSON.stringify(obj) .replace(/[‘{}]/g, ‘‘) .replace(/:/g, ‘=‘) .replace(/,/g, ‘&‘); return url; } else { return url; } } } /** * dom操作工具类 */ class DomClazz { /** * 类jq选择器 * @param selector * @returns {*} */ $(selector) { var type = selector.substring(0, 1); if (type === ‘#‘) { if (document.querySelecotor) return document.querySelector(selector); return document.getElementById(selector.substring(1)); } else if (type === ‘.‘) { if (document.querySelecotorAll) return document.querySelectorAll(selector); return document.getElementsByClassName(selector.substring(1)); } else { return document[ ‘querySelectorAll‘ ? ‘querySelectorAll‘ : ‘getElementsByTagName‘ ](selector); } } /*检测类名*/ hasClass(ele, name) { return ele.className.match(new RegExp(‘(\s|^)‘ + name + ‘(\s|$)‘)); } /*添加类名*/ addClass(ele, name) { if (!this.hasClass(ele, name)) ele.className += ‘ ‘ + name; } /*删除类名*/ removeClass(ele, name) { if (this.hasClass(ele, name)) { var reg = new RegExp(‘(\s|^)‘ + name + ‘(\s|$)‘); ele.className = ele.className.replace(reg, ‘‘); } } /*替换类名*/ replaceClass(ele, newName, oldName) { this.removeClass(ele, oldName); this.addClass(ele, newName); } /*获取兄弟节点*/ siblings(ele) { console.log(ele.parentNode); var chid = ele.parentNode.children, eleMatch = []; for (var i = 0, len = chid.length; i < len; i++) { if (chid[i] != ele) { eleMatch.push(chid[i]); } } return eleMatch; } /*获取行间样式属性*/ getByStyle(obj, name) { if (obj.currentStyle) { return obj.currentStyle[name]; } else { return getComputedStyle(obj, false)[name]; } } /** * 判断dom是否有指定样式,然后取反,由样式就删除,没有就增加 * @param element dom对象 * @param cls 样式名 */ toggleClass(element, cls) { if (hasClass(element, cls)) { removeClass(element, cls); } else { addClass(element, cls); } } /** * DOM转字符串 * @param htmlDOM * @returns {string} */ domToStirng(htmlDOM) { var div = document.createElement(‘div‘); div.appendChild(htmlDOM); return div.innerHTML; } /** * 字符串转DOM * @param htmlString * @returns {Element} */ stringToDom(htmlString) { var div = document.createElement(‘div‘); div.innerHTML = htmlString; return div.children[0]; } } /** * 数值操作工具类 */ class NumberClazz { /*随机数范围*/ random(min, max) { if (arguments.length === 2) { return Math.floor(min + Math.random() * (max + 1 - min)); } else { return null; } } /*将阿拉伯数字翻译成中文的大写数字*/ numberToChinese(num) { var AA = new Array( ‘零‘, ‘一‘, ‘二‘, ‘三‘, ‘四‘, ‘五‘, ‘六‘, ‘七‘, ‘八‘, ‘九‘, ‘十‘ ); var BB = new Array(‘‘, ‘十‘, ‘百‘, ‘仟‘, ‘萬‘, ‘億‘, ‘点‘, ‘‘); var a = (‘‘ + num).replace(/(^0*)/g, ‘‘).split(‘.‘), k = 0, re = ‘‘; for (var i = a[0].length - 1; i >= 0; i--) { switch (k) { case 0: re = BB[7] + re; break; case 4: if (!new RegExp(‘0{4}//d{‘ + (a[0].length - i - 1) + ‘}$‘).test(a[0])) re = BB[4] + re; break; case 8: re = BB[5] + re; BB[7] = BB[5]; k = 0; break; } if (k % 4 == 2 && a[0].charAt(i + 2) != 0 && a[0].charAt(i + 1) == 0) re = AA[0] + re; if (a[0].charAt(i) != 0) re = AA[a[0].charAt(i)] + BB[k % 4] + re; k++; } if (a.length > 1) { // 加上小数部分(如果有小数部分) re += BB[6]; for (var i = 0; i < a[1].length; i++) re += AA[a[1].charAt(i)]; } if (re == ‘一十‘) re = ‘十‘; if (re.match(/^一/) && re.length == 3) re = re.replace(‘一‘, ‘‘); return re; } /*将数字转换为大写金额*/ changeToChinese(Num) { //判断如果传递进来的不是字符的话转换为字符 if (typeof Num == ‘number‘) { Num = new String(Num); } Num = Num.replace(/,/g, ‘‘); //替换tomoney()中的“,” Num = Num.replace(/ /g, ‘‘); //替换tomoney()中的空格 Num = Num.replace(/¥/g, ‘‘); //替换掉可能出现的¥字符 if (isNaN(Num)) { //验证输入的字符是否为数字 //alert(‘请检查小写金额是否正确‘); return ‘‘; } //字符处理完毕后开始转换,采用前后两部分分别转换 var part = String(Num).split(‘.‘); var newchar = ‘‘; //小数点前进行转化 for (var i = part[0].length - 1; i >= 0; i--) { if (part[0].length > 10) { return ‘‘; //若数量超过拾亿单位,提示 } var tmpnewchar = ‘‘; var perchar = part[0].charAt(i); switch (perchar) { case ‘0‘: tmpnewchar = ‘零‘ + tmpnewchar; break; case ‘1‘: tmpnewchar = ‘壹‘ + tmpnewchar; break; case ‘2‘: tmpnewchar = ‘贰‘ + tmpnewchar; break; case ‘3‘: tmpnewchar = ‘叁‘ + tmpnewchar; break; case ‘4‘: tmpnewchar = ‘肆‘ + tmpnewchar; break; case ‘5‘: tmpnewchar = ‘伍‘ + tmpnewchar; break; case ‘6‘: tmpnewchar = ‘陆‘ + tmpnewchar; break; case ‘7‘: tmpnewchar = ‘柒‘ + tmpnewchar; break; case ‘8‘: tmpnewchar = ‘捌‘ + tmpnewchar; break; case ‘9‘: tmpnewchar = ‘玖‘ + tmpnewchar; break; } switch (part[0].length - i - 1) { case 0: tmpnewchar = tmpnewchar + ‘元‘; break; case 1: if (perchar != 0) tmpnewchar = tmpnewchar + ‘拾‘; break; case 2: if (perchar != 0) tmpnewchar = tmpnewchar + ‘佰‘; break; case 3: if (perchar != 0) tmpnewchar = tmpnewchar + ‘仟‘; break; case 4: tmpnewchar = tmpnewchar + ‘万‘; break; case 5: if (perchar != 0) tmpnewchar = tmpnewchar + ‘拾‘; break; case 6: if (perchar != 0) tmpnewchar = tmpnewchar + ‘佰‘; break; case 7: if (perchar != 0) tmpnewchar = tmpnewchar + ‘仟‘; break; case 8: tmpnewchar = tmpnewchar + ‘亿‘; break; case 9: tmpnewchar = tmpnewchar + ‘拾‘; break; } var newchar = tmpnewchar + newchar; } //小数点之后进行转化 if (Num.indexOf(‘.‘) != -1) { if (part[1].length > 2) { // alert(‘小数点之后只能保留两位,系统将自动截断‘); part[1] = part[1].substr(0, 2); } for (i = 0; i < part[1].length; i++) { tmpnewchar = ‘‘; perchar = part[1].charAt(i); switch (perchar) { case ‘0‘: tmpnewchar = ‘零‘ + tmpnewchar; break; case ‘1‘: tmpnewchar = ‘壹‘ + tmpnewchar; break; case ‘2‘: tmpnewchar = ‘贰‘ + tmpnewchar; break; case ‘3‘: tmpnewchar = ‘叁‘ + tmpnewchar; break; case ‘4‘: tmpnewchar = ‘肆‘ + tmpnewchar; break; case ‘5‘: tmpnewchar = ‘伍‘ + tmpnewchar; break; case ‘6‘: tmpnewchar = ‘陆‘ + tmpnewchar; break; case ‘7‘: tmpnewchar = ‘柒‘ + tmpnewchar; break; case ‘8‘: tmpnewchar = ‘捌‘ + tmpnewchar; break; case ‘9‘: tmpnewchar = ‘玖‘ + tmpnewchar; break; } if (i == 0) tmpnewchar = tmpnewchar + ‘角‘; if (i == 1) tmpnewchar = tmpnewchar + ‘分‘; newchar = newchar + tmpnewchar; } } //替换所有无用汉字 while (newchar.search(‘零零‘) != -1) newchar = newchar.replace(‘零零‘, ‘零‘); newchar = newchar.replace(‘零亿‘, ‘亿‘); newchar = newchar.replace(‘亿万‘, ‘亿‘); newchar = newchar.replace(‘零万‘, ‘万‘); newchar = newchar.replace(‘零元‘, ‘元‘); newchar = newchar.replace(‘零角‘, ‘‘); newchar = newchar.replace(‘零分‘, ‘‘); if (newchar.charAt(newchar.length - 1) == ‘元‘) { newchar = newchar + ‘整‘; } return newchar; } /** * @desc 千位分割方法 * @param {String,Number} num * @param {Number} n * @param {String} symbol * @return {String} * (123456789.11).toLocaleString(‘en-US‘) ie11+ 兼容性不好 *(d)(?=(d{3})+.)/g; *这里最难理解的就是(?=(d{3})+.),且看语法: *x(?=y):正向肯定查找,匹配后面带有y的x项目 *查找一个和“.”之间带有一个或多个连续3位数字的数字(x) *symbol 不建议为‘.‘ */ priceSubstr() { var num = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ‘0‘; var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var symbol = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ‘,‘; if (parseInt(num) != num && n !== 0) { if (symbol === ‘.‘) throw new Error(‘symbol can not same as .‘); } num = (+num).toFixed(n === 0 ? 1 : n); num = num.toString().replace(/(d)(?=(d{3})+.)/g, ‘$1‘ + symbol); if (!!n) { return num; } else { return num.substring(0, num.lastIndexOf(‘.‘)); } } } /** * cookie session,localStorage相关工具类 */ class StorageClazz { constructor() { this.ls = window.localStorage; this.ss = window.sessionStorage; } /*-----------------cookie---------------------*/ /** * 添加cookie * @param name cookie名字 * @param value cookie内容 * @param day 过期时间 * 如果过期时间未设置,默认管理浏览器自动删除 * 例子: * cookieData.set(‘name‘,‘value‘,) */ setCookie(name, value, day) { var setting = arguments[0]; if (Object.prototype.toString.call(setting).slice(8, -1) === ‘Object‘) { for (var i in setting) { var oDate = new Date(); oDate.setDate(oDate.getDate() + day); document.cookie = i + ‘=‘ + setting[i] + ‘;expires=‘ + oDate; } } else { var oDate = new Date(); oDate.setDate(oDate.getDate() + day); document.cookie = name + ‘=‘ + value + ‘;expires=‘ + oDate; } } /** * 根据名字获取cooki值 * @param name cookie名 * @returns {*} cookie值 */ getCookie(name) { var arr = document.cookie.split(‘; ‘); for (var i = 0; i < arr.length; i++) { var arr2 = arr[i].split(‘=‘); if (arr2[0] == name) { return arr2[1]; } } return ‘‘; } /** * 根据cookie名字删除cookie * @param name cookie名字 */ removeCookie(name) { this.setCookie(name, 1, -1); } /*-----------------localStorage---------------------*/ /*设置localStorage*/ setLocal(key, val) { var setting = arguments[0]; if (Object.prototype.toString.call(setting).slice(8, -1) === ‘Object‘) { for (var i in setting) { this.ls.setItem(i, JSON.stringify(setting[i])); } } else { this.ls.setItem(key, JSON.stringify(val)); } } /*获取localStorage*/ getLocal(key) { if (key) return JSON.parse(this.ls.getItem(key)); return null; } /*移除localStorage*/ removeLocal(key) { this.ls.removeItem(key); } /*移除所有localStorage*/ clearLocal() { this.ls.clear(); } /*-----------------sessionStorage---------------------*/ /*设置sessionStorage*/ setSession(key, val) { var setting = arguments[0]; if (Object.prototype.toString.call(setting).slice(8, -1) === ‘Object‘) { for (var i in setting) { this.ss.setItem(i, JSON.stringify(setting[i])); } } else { this.ss.setItem(key, JSON.stringify(val)); } } /*获取sessionStorage*/ getSession(key) { if (key) return JSON.parse(this.ss.getItem(key)); return null; } /*移除sessionStorage*/ removeSession(key) { this.ss.removeItem(key); } /*移除所有sessionStorage*/ clearSession() { this.ss.clear(); } } /** * 校验工具类 */ class ValidateClazz { /** * 校验所输入的身份证是否是正确的身份证号码 * 不止校验格式,需要正确的身份证号码才能校验通过 * @param code 身份证号码 * @returns {boolean} true:是 false:不是 */ idCardRegexs(code) { let city = { 11: ‘北京‘, 12: ‘天津‘, 13: ‘河北‘, 14: ‘山西‘, 15: ‘内蒙古‘, 21: ‘辽宁‘, 22: ‘吉林‘, 23: ‘黑龙江 ‘, 31: ‘上海‘, 32: ‘江苏‘, 33: ‘浙江‘, 34: ‘安徽‘, 35: ‘福建‘, 36: ‘江西‘, 37: ‘山东‘, 41: ‘河南‘, 42: ‘湖北 ‘, 43: ‘湖南‘, 44: ‘广东‘, 45: ‘广西‘, 46: ‘海南‘, 50: ‘重庆‘, 51: ‘四川‘, 52: ‘贵州‘, 53: ‘云南‘, 54: ‘西藏 ‘, 61: ‘陕西‘, 62: ‘甘肃‘, 63: ‘青海‘, 64: ‘宁夏‘, 65: ‘新疆‘, 71: ‘台湾‘, 81: ‘香港‘, 82: ‘澳门‘, 91: ‘国外 ‘ }; let tip = ‘‘; let pass = true; if (!code || !/(^d{15}$)|(^d{18}$)|(^d{17}(d|X|x)$)/.test(code)) { tip = ‘身份证号格式错误‘; pass = false; } else if (!city[code.substr(0, 2)]) { tip = ‘身份证号格式错误‘; pass = false; } else { // 18位身份证需要验证最后一位校验位 if (code.length === 18) { code = code.split(‘‘); // ∑(ai×Wi)(mod 11) // 加权因子 let factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; // 校验位 let parity = [1, 0, ‘X‘, 9, 8, 7, 6, 5, 4, 3, 2]; let sum = 0; let ai = 0; let wi = 0; for (let i = 0; i < 17; i++) { ai = code[i]; wi = factor[i]; sum += ai * wi; } let last = parity[sum % 11]; if (last != code[17]) { tip = ‘身份证号格式错误‘; pass = false; } } } console.log(tip); return pass; } /** * 正则校验 * @param str 需要校验的字符串 * @param type 校验类型字符串 * @returns {boolean} */ checkStr(str, type) { switch (type) { case ‘phone‘: //手机号码 return /^1[3|4|5|7|8][0-9]{9}$/.test(str); case ‘tel‘: //座机 return /^(0d{2,3}-d{7,8})(-d{1,4})?$/.test(str); case ‘card‘: //身份证 return /(^d{15}$)|(^d{18}$)|(^d{17}(d|X|x)$)/.test(str); case ‘pwd‘: //密码以字母开头,长度在6~18之间,只能包含字母、数字和下划线 return /^[a-zA-Z]w{5,17}$/.test(str); case ‘postal‘: //邮政编码 return /[1-9]d{5}(?!d)/.test(str); case ‘QQ‘: //QQ号 return /^[1-9][0-9]{4,9}$/.test(str); case ‘email‘: //邮箱 return /^[-w+]+(?:.[-w]+)*@[-a-z0-9]+(?:.[a-z0-9]+)*(?:.[a-z]{2,})$/i.test( str ); case ‘money‘: //金额(小数点2位) return /^d*(?:.d{0,2})?$/.test(str); case ‘URL‘: //网址 return /(http|ftp|https)://[w-_]+(.[w-_]+)+([w-.,@?^=%&:/~+#]*[w-@?^=%&/~+#])?/.test( str ); case ‘IP‘: //IP return /((?:(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d?\d))/.test( str ); case ‘date‘: //日期时间 return ( /^(d{4})-(d{2})-(d{2}) (d{2})(?::d{2}|:(d{2}):(d{2}))$/.test( str ) || /^(d{4})-(d{2})-(d{2})$/.test(str) ); case ‘number‘: //数字 return /^[0-9]$/.test(str); case ‘english‘: //英文 return /^[a-zA-Z]+$/.test(str); case ‘chinese‘: //中文 return /^[u4E00-u9FA5]+$/.test(str); case ‘lower‘: //小写 return /^[a-z]+$/.test(str); case ‘upper‘: //大写 return /^[A-Z]+$/.test(str); case ‘HTML‘: //HTML标记 return /<(‘[^‘]*‘|‘[^‘]*‘|[^‘‘>])*>/.test(str); default: return true; } } } /** * 其他一些工具类 */ class CommonClazz { /** * 对比两个对象是否相等,可以是字符串,数值,数组, * @param a * @param b * @returns {boolean} */ valueEquals(a, b) { if (a === b) return true; if (!(a instanceof Array)) return false; if (!(b instanceof Array)) return false; if (a.length !== b.length) return false; for (let i = 0; i !== a.length; ++i) { if (a[i] !== b[i]) return false; } return true; } /** * 获取十六进制随机颜色 * @returns {string} */ getRandomColor() { return ( ‘#‘ + (function(h) { return new Array(7 - h.length).join(‘0‘) + h; })(((Math.random() * 0x1000000) << 0).toString(16)) ); } /** * 根据身份证号码获取出生日期 * @param cardNo 身份证号码 * @returns {*} 出生日期 * 例子: * let cardNo=350681199311086518 * getBirthDate(cardNo) //返回 1993-11-08 */ getBirthDate(cardNo) { let len = cardNo.length; let birthday; let reFifteen; let arrData; let year; let month; let day; let reEighteen; if (len == ‘15‘) { reFifteen = /^(d{6})(d{2})(d{2})(d{2})(d{3})$/; arrData = cardNo.match(reFifteen); year = arrData[2]; month = arrData[3]; day = arrData[4]; birthday = ‘19‘ + year + ‘-‘ + month + ‘-‘ + day; } // 身份证18位时,次序为省(3位)市(3位)年(4位)月(2位)日(2位)校验位(4位),校验位末尾可能为X if (len == ‘18‘) { reEighteen = /^(d{6})(d{4})(d{2})(d{2})(d{3})([0-9]|X)$/; arrData = cardNo.match(reEighteen); year = arrData[2]; month = arrData[3]; day = arrData[4]; birthday = year + ‘-‘ + month + ‘-‘ + day; } return birthday; } /** * 图片加载 * @param arr * @param callback */ imgLoadAll(arr, callback) { var arrImg = []; for (var i = 0; i < arr.length; i++) { var img = new Image(); img.src = arr[i]; img.onload = function() { arrImg.push(this); if (arrImg.length == arr.length) { callback && callback(); } }; } } /** * 光标所在位置插入字符,并设置光标位置 * @param {dom} 输入框 * @param {val} 插入的值 * @param {posLen} 光标位置处在 插入的值的哪个位置 */ setCursorPosition(dom, val, posLen) { var cursorPosition = 0; if (dom.selectionStart) { cursorPosition = dom.selectionStart; } this.insertAtCursor(dom, val); dom.focus(); console.log(posLen); dom.setSelectionRange( dom.value.length, cursorPosition + (posLen || val.length) ); } /** * 光标所在位置插入字符 * @param dom * @param val */ insertAtCursor(dom, val) { if (document.selection) { dom.focus(); sel = document.selection.createRange(); sel.text = val; sel.select(); } else if (dom.selectionStart || dom.selectionStart == ‘0‘) { let startPos = dom.selectionStart; let endPos = dom.selectionEnd; let restoreTop = dom.scrollTop; dom.value = dom.value.substring(0, startPos) + val + dom.value.substring(endPos, dom.value.length); if (restoreTop > 0) { dom.scrollTop = restoreTop; } dom.focus(); dom.selectionStart = startPos + val.length; dom.selectionEnd = startPos + val.length; } else { dom.value += val; dom.focus(); } } /** * @desc 节流函数 * @param {Function} callBack * @return {Function} fn */ throttle(fn) { var delay = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 500; var _self = fn, //需要被延迟执行的函数引用 timer = void 0, firstTime = true; //是否第一次调用 return function() { var _this = this; var args = arguments; if (firstTime) { //第一次调用不用延迟 _self.apply(this, args); firstTime = false; } if (timer) { //timer还在没结束前一次 return false; } timer = setTimeout(function() { //延迟执行 clearTimeout(timer); timer = null; //手动释放timer _self.apply(_this, args); }, delay); }; } } /** * 导出工具类 */ export const ArrayUtil = new ArrayClazz(); export const StringUtil = new StringClazz(); export const DateUtil = new DateClazz(); export const ValidateUtil = new ValidateClazz(); export const DomUtil = new DomClazz(); export const UrlUtil = new urlClazz(); export const TypeUtil = new TypeClazz(); export const CommonUtil = new CommonClazz(); export const StorageUtil = new StorageClazz(); export const NumberUtil = new NumberClazz(); /** * 导出所有工具类 */ export default { ArrayUtil, StringUtil, DateUtil, ValidateUtil, DomUtil, UrlUtil, TypeUtil, CommonUtil, StorageUtil, NumberUtil };
以上是关于工具类的主要内容,如果未能解决你的问题,请参考以下文章