打造自己的Javascript工具類庫
阿新 • • 發佈:2019-01-13
基本擴充套件、工具包
// ------------------------ 基本擴充套件, 字串,陣列等---------------------------------// function extend_base (){ if(!String.prototype.format ){ String.prototype.format = function() { var e = arguments; return this.replace(/{(\d+)}/g,function(t, n) { return typeof e[n] != "undefined" ? e[n] : t }) }; } if (!Array.prototype.forEach && typeof Array.prototype.forEach !== "function") { Array.prototype.forEach = function(callback, context) { // 遍歷陣列,在每一項上呼叫回撥函式,這裡使用原生方法驗證陣列。 if (Object.prototype.toString.call(this) === "[object Array]") { var i,len; //遍歷該陣列所有的元素 for (i = 0, len = this.length; i < len; i++) { if (typeof callback === "function" && Object.prototype.hasOwnProperty.call(this, i)) { if (callback.call(context, this[i], i, this) === false) { break; // or return; } } } } }; } if(!String.prototype.format ){ Array.isArray = function(obj){ return obj.constructor.toString().indexOf('Array') != -1; } } } extend_base();
//------------------------------------------------------工具包---------------------------------------------//
/*1.1.4*/ var utils = { //****************************字串****************************/ //去除空格 type 1-所有空格 2-前後空格 3-前空格 4-後空格 //trim(' 1235asd',1) //result:1235asd trim: function (str, type) { 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; } }, /*type 1: 首字母大寫 2:首字母小寫 3:大小寫轉換 4:全部大寫 5:全部小寫 * */ //changeCase('asdasd',1) //result:Asdasd changeCase: function (str, type) { function ToggleCase(str) { var itemText = "" str.split("").forEach( function (item) { if (/^([a-z]+)/.test(item)) { itemText += item.toUpperCase(); } else if (/^([A-Z]+)/.test(item)) { itemText += item.toLowerCase(); } else { itemText += item; } }); return itemText; } switch (type) { case 1: return str.replace(/\b\w+\b/g, function (word) { return word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase(); }); case 2: return str.replace(/\b\w+\b/g, function (word) { return word.substring(0, 1).toLowerCase() + word.substring(1).toUpperCase(); }); case 3: return ToggleCase(str); case 4: return str.toUpperCase(); case 5: return str.toLowerCase(); default: return str; } }, //字串迴圈複製 //repeatStr(str->字串, count->次數) //repeatStr('123',3) //"result:123123123" repeatStr: function (str, count) { var text = ''; for (var i = 0; i < count; i++) { text += str; } return text; }, //字串替換(字串,要替換的字元或者正則表示式(不要寫g),替換成什麼) //ecDo.replaceAll('這裡是上海,中國第三大城市,廣東省省會,簡稱穗,','上海','廣州') //result:"這裡是廣州,中國第三大城市,廣東省省會,簡稱穗," replaceAll: function (str, AFindText, ARepText) { raRegExp = new RegExp(AFindText, "g"); return str.replace(raRegExp, ARepText); }, //字元替換* //replaceStr(字串,字元格式, 替換方式,替換的字元(預設*)) replaceStr: function (str, regArr, type, ARepText) { var regtext = '', Reg = null, replaceText = ARepText || '*'; //replaceStr('18819322663',[3,5,3],0) //result:188*****663 //repeatStr是在上面定義過的(字串迴圈複製),大家注意哦 if (regArr.length === 3 && type === 0) { regtext = '(\\w{' + regArr[0] + '})\\w{' + regArr[1] + '}(\\w{' + regArr[2] + '})' Reg = new RegExp(regtext); var replaceCount = this.repeatStr(replaceText, regArr[1]); return str.replace(Reg, '$1' + replaceCount + '$2') } //replaceStr('asdasdasdaa',[3,5,3],1) //result:***asdas*** else if (regArr.length === 3 && type === 1) { regtext = '\\w{' + regArr[0] + '}(\\w{' + regArr[1] + '})\\w{' + regArr[2] + '}' Reg = new RegExp(regtext); var replaceCount1 = this.repeatStr(replaceText, regArr[0]); var replaceCount2 = this.repeatStr(replaceText, regArr[2]); return str.replace(Reg, replaceCount1 + '$1' + replaceCount2) } //replaceStr('1asd88465asdwqe3',[5],0) //result:*****8465asdwqe3 else if (regArr.length === 1 && type === 0) { regtext = '(^\\w{' + regArr[0] + '})' Reg = new RegExp(regtext); var replaceCount = this.repeatStr(replaceText, regArr[0]); return str.replace(Reg, replaceCount) } //replaceStr('1asd88465asdwqe3',[5],1,'+') //result:"1asd88465as+++++" else if (regArr.length === 1 && type === 1) { regtext = '(\\w{' + regArr[0] + '}$)' Reg = new RegExp(regtext); var replaceCount = this.repeatStr(replaceText, regArr[0]); return str.replace(Reg, replaceCount) } }, //檢測字串 //checkType('165226226326','phone') //result:false //大家可以根據需要擴充套件 checkType: function (str, type) { switch (type) { case 'email': return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str); case 'phone': return /^1[3|4|5|7|8][0-9]{9}$/.test(str); case 'tel': return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str); case 'number': return /^[0-9]$/.test(str); case 'english': return /^[a-zA-Z]+$/.test(str); case 'text': return /^\w+$/.test(str); case 'chinese': return /^[\u4E00-\u9FA5]+$/.test(str); case 'lower': return /^[a-z]+$/.test(str); case 'upper': return /^[A-Z]+$/.test(str); default: return true; } }, //檢測密碼強度 //checkPwd('12asdASAD') //result:3(強度等級為3) checkPwd: function (str) { var nowLv = 0; if (str.length < 6) { return nowLv } if (/[0-9]/.test(str)) { nowLv++ } if (/[a-z]/.test(str)) { nowLv++ } if (/[A-Z]/.test(str)) { nowLv++ } if (/[\.|-|_]/.test(str)) { nowLv++ } return nowLv; }, //隨機碼 //count取值範圍2-36 //randomWord(10) //result:"2584316588472575" //randomWord(14) //result:"9b405070dd00122640c192caab84537" //randomWord(36) //result:"83vhdx10rmjkyb9" randomWord: function (count) { return Math.random().toString(count).substring(2); }, //查詢字串 //var strTest='sad44654blog5a1sd67as9dablog4s5d16zxc4sdweasjkblogwqepaskdkblogahseiuadbhjcibloguyeajzxkcabloguyiwezxc967' //countStr(strTest,'blog') //result:6 countStr: function (str, strSplit) { return str.split(strSplit).length - 1 }, //過濾字串(html標籤,表情,特殊字元) //字串,替換內容(special-特殊字元,html-html標籤,emjoy-emjoy表情,word-小寫字母,WORD-大寫字母,number-數字,chinese-中文),要替換成什麼,預設'',保留哪些特殊字元 //如果需要過濾多種字元,type引數使用,分割,如下栗子 //過濾字串的html標籤,大寫字母,中文,特殊字元,全部替換成*,但是特殊字元'%','?',除了這兩個,其他特殊字元全部清除 //var str='asd 654a大蠢sasdasdASDQWEXZC6d5#%^*^&*^%^&*$\\"\'#@!()*/-())_\'":"{}?<div></div><img src=""/>啊實打實大蠢豬自行車這些課程'; // ecDo.filterStr(str,'html,WORD,chinese,special','*','%?') //result:"asd 654a**sasdasd*********6d5#%^*^&*^%^&*$\"'#@!()*/-())_'":"{}?*****************" filterStr: function (str, type, restr, spstr) { var typeArr = type.split(','), _str = str; for (var i = 0, len = typeArr.length; i < len; i++) { //是否是過濾特殊符號 if (typeArr[i] === 'special') { var pattern, regText = '$()[]{}?\|^*+./\"\'+'; //是否有哪些特殊符號需要保留 if (spstr) { var _spstr = spstr.split(""), _regText = "[^0-9A-Za-z\\s"; for (var j = 0, len1 = _spstr.length; j < len1; j++) { if (regText.indexOf(_spstr[j]) === -1) { _regText += _spstr[j]; } else { _regText += '\\' + _spstr[j]; } } _regText += ']' pattern = new RegExp(_regText, 'g'); } else { pattern = new RegExp("[^0-9A-Za-z\\s]", 'g') } } var _restr = restr || ''; switch (typeArr[i]) { case 'special': _str = _str.replace(pattern, _restr); break; case 'html': _str = _str.replace(/<\/?[^>]*>/g, _restr); break; case 'emjoy': _str = _str.replace(/[^\u4e00-\u9fa5|\u0000-\u00ff|\u3002|\uFF1F|\uFF01|\uff0c|\u3001|\uff1b|\uff1a|\u3008-\u300f|\u2018|\u2019|\u201c|\u201d|\uff08|\uff09|\u2014|\u2026|\u2013|\uff0e]/g, _restr); break; case 'word': _str = _str.replace(/[a-z]/g, _restr); break; case 'WORD': _str = _str.replace(/[A-Z]/g, _restr); break; case 'number': _str = _str.replace(/[0-9]/g, _restr); break; case 'chinese': _str = _str.replace(/[\u4E00-\u9FA5]/g, _restr); break; } } return _str; }, //格式化處理字串 //ecDo.formatText('1234asda567asd890') //result:"12,34a,sda,567,asd,890" //ecDo.formatText('1234asda567asd890',4,' ') //result:"1 234a sda5 67as d890" //ecDo.formatText('1234asda567asd890',4,'-') //result:"1-234a-sda5-67as-d890" formatText: function (str, size, delimiter) { var _size = size || 3, _delimiter = delimiter || ','; var regText = '\\B(?=(\\w{' + _size + '})+(?!\\w))'; var reg = new RegExp(regText, 'g'); return str.replace(reg, _delimiter); }, //找出最長單詞 (Find the Longest word in a String) //longestWord('Find the Longest word in a String') //result:7 //longestWord('Find|the|Longest|word|in|a|String','|') //result:7 longestWord: function (str, splitType) { var _splitType = splitType || /\s+/g, _max = 0,_item=''; var strArr = str.split(_splitType); strArr.forEach(function (item) { if (_max < item.length) { _max = item.length _item=item; } }) return {el:_item,max:_max}; }, //句中單詞首字母大寫 (Title Case a Sentence) //這個我也一直在糾結,英文標題,即使是首字母大寫,也未必每一個單詞的首字母都是大寫的,但是又不知道哪些應該大寫,哪些不應該大寫 //ecDo.titleCaseUp('this is a title') //"This Is A Title" titleCaseUp: function (str, splitType) { var _splitType = splitType || /\s+/g; var strArr = str.split(_splitType), result = "", _this = this strArr.forEach(function (item) { result += _this.changeCase(item, 1) + ' '; }) return this.trim(result, 4) }, //****************************陣列*****************************/ //陣列去重 removeRepeatArray: function (arr) { return arr.filter(function (item, index, self) { return self.indexOf(item) === index; }); //es6 //return Array.from(new Set(arr)) }, //陣列順序打亂 upsetArr: function (arr) { return arr.sort(function () { return Math.random() - 0.5 }); }, //陣列最大值 //這一塊的封裝,主要是針對數字型別的陣列 maxArr: function (arr) { return Math.max.apply(null, arr); }, //陣列最小值 minArr: function (arr) { return Math.min.apply(null, arr); }, //這一塊的封裝,主要是針對數字型別的陣列 //陣列求和 sumArr: function (arr) { return arr.reduce(function (pre, cur) { return pre + cur }) }, //陣列平均值,小數點可能會有很多位,這裡不做處理,處理了使用就不靈活了! covArr: function (arr) { return this.sumArr(arr) / arr.length; }, //從陣列中隨機獲取元素 randomOne: function (arr) { return arr[Math.floor(Math.random() * arr.length)]; }, //回陣列(字串)一個元素出現的次數 //getEleCount('asd56+asdasdwqe','a') //result:3 //getEleCount([1,2,3,4,5,66,77,22,55,22],22) //result:2 getEleCount: function (obj, ele) { var num = 0; for (var i = 0, len = obj.length; i < len; i++) { if (ele === obj[i]) { num++; } } return num; }, //返回陣列(字串)出現最多的幾次元素和出現次數 //arr, rank->長度,預設為陣列長度,ranktype,排序方式,預設降序 //返回值:el->元素,count->次數 //getCount([1,2,3,1,2,5,2,4,1,2,6,2,1,3,2]) //result:[{"el":"2","count":6},{"el":"1","count":4},{"el":"3","count":2},{"el":"4","count":1},{"el":"5","count":1},{"el":"6","count":1}] //預設情況,返回所有元素出現的次數 //getCount([1,2,3,1,2,5,2,4,1,2,6,2,1,3,2],3) //傳參(rank=3),只返回出現次數排序前三的 //result:[{"el":"2","count":6},{"el":"1","count":4},{"el":"3","count":2}] //getCount([1,2,3,1,2,5,2,4,1,2,6,2,1,3,2],null,1) //傳參(ranktype=1,rank=null),升序返回所有元素出現次數 //result:[{"el":"6","count":1},{"el":"5","count":1},{"el":"4","count":1},{"el":"3","count":2},{"el":"1","count":4},{"el":"2","count":6}] //getCount([1,2,3,1,2,5,2,4,1,2,6,2,1,3,2],3,1) //傳參(rank=3,ranktype=1),只返回出現次數排序(升序)前三的 //result:[{"el":"6","count":1},{"el":"5","count":1},{"el":"4","count":1}] getCount: function (arr, rank, ranktype) { var obj = {}, k, arr1 = [] //記錄每一元素出現的次數 for (var i = 0, len = arr.length; i < len; i++) { k = arr[i]; if (obj[k]) { obj[k]++; } else { obj[k] = 1; } } //儲存結果{el-'元素',count-出現次數} for (var o in obj) { arr1.push({el: o, count: obj[o]}); } //排序(降序) arr1.sort(function (n1, n2) { return n2.count - n1.count }); //如果ranktype為1,則為升序,反轉陣列 if (ranktype === 1) { arr1 = arr1.reverse(); } var rank1 = rank || arr1.length; return arr1.slice(0, rank1); }, //得到n1-n2下標的陣列 //getArrayNum([0,1,2,3,4,5,6,7,8,9],5,9) //result:[5, 6, 7, 8, 9] //getArrayNum([0,1,2,3,4,5,6,7,8,9],2) 不傳第二個引數,預設返回從n1到陣列結束的元素 //result:[2, 3, 4, 5, 6, 7, 8, 9] getArrayNum: function (arr, n1, n2) { return arr.slice(n1, n2); }, //篩選陣列 //刪除值為'val'的陣列元素 //removeArrayForValue(['test','test1','test2','test','aaa'],'test','%') //result:["aaa"] 帶有'test'的都刪除 //removeArrayForValue(['test','test1','test2','test','aaa'],'test') //result:["test1", "test2", "aaa"] //陣列元素的值全等於'test'才被刪除 removeArrayForValue: function (arr, val, type) { return arr.filter(function (item) { return type ? item.indexOf(val) === -1 : item !== val }) }, //獲取物件陣列某些項 //var arr=[{a:1,b:2,c:9},{a:2,b:3,c:5},{a:5,b:9},{a:4,b:2,c:5},{a:4,b:5,c:7}] //getOptionArray(arr,'a,c') //result:[{a:1,c:9},{a:2,c:5},{a:5,c:underfind},{a:4,c:5},{a:4,c:7}] //getOptionArray(arr,'b',1) //result:[2, 3, 9, 2, 5] getOptionArray: function (arr, keys) { var newArr = [] if (!keys) { return arr } var _keys = keys.split(','), newArrOne = {}; //是否只是需要獲取某一項的值 if (_keys.length === 1) { for (var i = 0, len = arr.length; i < len; i++) { newArr.push(arr[i][keys]) } return newArr; } for (var i = 0, len = arr.length; i < len; i++) { newArrOne = {}; for (var j = 0, len1 = _keys.length; j < len1; j++) { newArrOne[_keys[j]] = arr[i][_keys[j]] } newArr.push(newArrOne); } return newArr }, //排除陣列某些項 //var arr=[{a:1,b:2,c:9},{a:2,b:3,c:5},{a:5,b:9},{a:4,b:2,c:5},{a:4,b:5,c:7}] //filterOptionArray(arr,'a') //result:[{b:2,c:9},{b:3,c:5},{b:9},{b:2,c:5},{b:5,c:7}] //filterOptionArray(arr,'a,c') //result:[{b:2},{b:3},{b:9},{b:2},{b:5}] filterOptionArray: function (arr, keys) { var newArr = [] var _keys = keys.split(','), newArrOne = {}; for (var i = 0, len = arr.length; i < len; i++) { newArrOne = {}; for (var key in arr[i]) { //如果key不存在排除keys裡面,新增資料 if (_keys.indexOf(key) === -1) { newArrOne[key] = arr[i][key]; } } newArr.push(newArrOne); } return newArr }, //物件陣列的排序 //var arr=[{a:1,b:2,c:9},{a:2,b:3,c:5},{a:5,b:9},{a:4,b:2,c:5},{a:4,b:5,c:7}] //ecDo.arraySort(arr,'a,b')a是第一排序條件,b是第二排序條件 //result:[{"a":1,"b":2,"c":9},{"a":2,"b":3,"c":5},{"a":4,"b":2,"c":5},{"a":4,"b":5,"c":7},{"a":5,"b":9}] arraySort: function (arr, sortText) { if (!sortText) { return arr } var _sortText = sortText.split(',').reverse(), _arr = arr.slice(0); for (var i = 0, len = _sortText.length; i < len; i++) { _arr.sort(function (n1, n2) { return n1[_sortText[i]] - n2[_sortText[i]] }) } return _arr; }, //陣列扁平化 steamroller: function (arr) { var newArr = [],_this=this; for (var i = 0; i < arr.length; i++) { if (Array.isArray(arr[i])) { // 如果是陣列,呼叫(遞迴)steamroller 將其扁平化 // 然後再 push 到 newArr 中 newArr.push.apply(newArr, _this.steamroller(arr[i])); } else { // 不是陣列直接 push 到 newArr 中 newArr.push(arr[i]); } } return newArr; }, //另一種寫法 //steamroller([1,2,[4,5,[1,23]]]) //[1, 2, 4, 5, 1, 23] /* * i=0 newArr.push(arr[i]) [1] * i=1 newArr.push(arr[i]) [1,2] * i=2 newArr = newArr.concat(steamroller(arr[i])); 執行到下面 * 第一次i=2進入後 i=0, newArr.push(arr[i]); [4] * 第一次i=2進入後 i=1, newArr.push(arr[i]); [4,5] * * i=2 newArr = newArr.concat(steamroller(arr[i])); 執行到下面 * 第二次i=2進入後 i=0, newArr.push(arr[i]); [1] * 第二次i=2進入後 i=1, newArr.push(arr[i]); [1,23] 執行到下面 * 第二次迴圈完,回到第一次進入後 newArr = newArr.concat(steamroller(arr[i])); [4,5].concat([1,23]) [4,5,1,23] * 然後回到第一次 [1,2].concat([4,5,1,23]) */ // steamroller: function (arr) { // var newArr = []; // for (var i = 0; i < arr.length; i++) { // if (Array.isArray(arr[i])) { // // 如果是陣列,呼叫(遞迴)steamroller 將其扁平化 // // 然後再 push 到 newArr 中 // newArr = newArr.concat(steamroller(arr[i])); // } else { // // 不是陣列直接 push 到 newArr 中 // newArr.push(arr[i]); // } // } // return newArr; // }, //****************************物件及其他*****************************/ //適配rem getFontSize: function (_client) { var doc = document, win = window; var docEl = doc.documentElement, resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize', recalc = function () { var clientWidth = docEl.clientWidth; if (!clientWidth) return; //如果螢幕大於750(750是根據我效果圖設定的,具體數值參考效果圖),就設定clientWidth=750,防止font-size會超過100px if (clientWidth > _client) { clientWidth = _client } //設定根元素font-size大小 docEl.style.fontSize = 100 * (clientWidth / _client) + 'px'; }; //螢幕大小改變,或者橫豎屏切換時,觸發函式 win.addEventListener(resizeEvt, recalc, false); //文件載入完成時,觸發函式 doc.addEventListener('DOMContentLoaded', recalc, false); }, //到某一個時間的倒計時 //getEndTime('2017/7/22 16:0:0') //result:"剩餘時間6天 2小時 28 分鐘20 秒" getEndTime: function (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 + " 秒"; }, //隨進產生顏色 randomColor: function () { //randomNumber是下面定義的函式 //寫法1 //return 'rgb(' + this.randomNumber(255) + ',' + this.randomNumber(255) + ',' + this.randomNumber(255) + ')'; //寫法2 return '#' + Math.random().toString(16).substring(2).substr(0, 6); //寫法3 //var color='#',_index=this.randomNumber(15); //for(var i=0;i<6;i++){ //color+='0123456789abcdef'[_index]; //} //return color; }, //隨機返回一個範圍的數字 randomNumber: function (n1, n2) { //randomNumber(5,10) //返回5-10的隨機整數,包括5,10 if (arguments.length === 2) { return Math.round(n1 + Math.random() * (n2 - n1)); } //randomNumber(10) //返回0-10的隨機整數,包括0,10 else if (arguments.length === 1) { return Math.round(Math.random() * n1) } //randomNumber() //返回0-255的隨機整數,包括0,255 else { return Math.round(Math.random() * 255) } }, //設定url引數 //setUrlPrmt({'a':1,'b':2}) //result:a=1&b=2 setUrlPrmt: function (obj) { var _rs = []; for (var p in obj) { if (obj[p] != null && obj[p] != '') { _rs.push(p + '=' + obj[p]) } } return _rs.join('&'); }, //獲取url引數 //getUrlPrmt('segmentfault.com/write?draftId=122000011938') //result:Object{draftId: "122000011938"} getUrlPrmt: function (url) { 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; }, //現金額大寫轉換函式 //upDigit(168752632) //result:"人民幣壹億陸仟捌佰柒拾伍萬貳仟陸佰叄拾貳元整" //upDigit(1682) //result:"人民幣壹仟陸佰捌拾貳元整" //upDigit(-1693) //result:"欠人民幣壹仟陸佰玖拾叄元整" upDigit: function (n) { var fraction = ['角', '分', '釐']; var digit = ['零', '壹', '貳', '叄', '肆', '伍', '陸', '柒', '捌', '玖']; var unit = [ ['元', '萬', '億'], ['', '拾', '佰', '仟'] ]; var head = n < 0 ? '欠人民幣' : '人民幣'; n = Math.abs(n); var s = ''; for (var 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 (var i = 0; i < unit[0].length && n > 0; i++) { var p = ''; for (var 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; //s = p + unit[0][i] + s; } return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整'); }, //清除物件中值為空的屬性 //filterParams({a:"",b:null,c:"010",d:123}) //Object {c: "010", d: 123} filterParams: function (obj) { var _newPar = {}; for (var key in obj) { if ((obj[key] === 0 ||obj[key] === false|| obj[key]) && obj[key].toString().replace(/(^\s*)|(\s*$)/g, '') !== '') { _newPar[key] = obj[key]; } } return _newPar; }, //****************************cookie****************************/ //設定cookie setCookie: function (name, value, iDay) { var oDate = new Date(); oDate.setDate(oDate.getDate() + iDay); document.cookie = name + '=' + value + ';expires=' + oDate; }, //獲取cookie getCookie: function (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 removeCookie: function (name) { this.setCookie(name, 1, -1); }, /*DOM*/ //檢測物件是否有哪個類名 hasClass: function (obj, classStr) { if (obj.className && this.trim(obj.className, 1) !== "") { var arr = obj.className.split(/\s+/); //這個正則表示式是因為class可以有多個,判斷是否包含 return (arr.indexOf(classStr) == -1) ? false : true; } else { return false; } }, //新增類名 addClass: function (obj, classStr) { if ((this.istype(obj, 'array') || this.istype(obj, 'elements')) && obj.length >= 1) { for (var i = 0, len = obj.length; i < len; i++) { if (!this.hasClass(obj[i], classStr)) { obj[i].className += " " + classStr; } } } else { if (!this.hasClass(obj, classStr)) { obj.className += " " + classStr; } } }, //刪除類名 removeClass: function (obj, classStr) { if ((this.istype(obj, 'array') || this.istype(obj, 'elements')) && obj.length > 1) { for (var i = 0, len = obj.length; i < len; i++) { if (this.hasClass(obj[i], classStr)) { var reg = new RegExp('(\\s|^)' + classStr + '(\\s|$)'); obj[i].className = obj[i].className.replace(reg, ''); } } } else { if (this.hasClass(obj, classStr)) { var reg = new RegExp('(\\s|^)' + classStr + '(\\s|$)'); obj.className = obj.className.replace(reg, ''); } } }, //替換類名("被替換的類名","替換的類名") replaceClass: function (obj, newName, oldName) { this.removeClass(obj, oldName); this.addClass(obj, newName); }, //獲取兄弟節點 //ecDo.siblings(obj,'#id') siblings: function (obj, opt) { var a = []; //定義一個數組,用來存o的兄弟元素 var p = obj.previousSibling; while (p) { //先取o的哥哥們 判斷有沒有上一個哥哥元素,如果有則往下執行 p表示previousSibling if (p.nodeType === 1) { a.push(p); } p = p.previousSibling //最後把上一個節點賦給p } a.reverse() //把順序反轉一下 這樣元素的順序就是按先後的了 var n = obj.nextSibling; //再取o的弟弟 while (n) { //判斷有沒有下一個弟弟結點 n是nextSibling的意思 if (n.nodeType === 1) { a.push(n); } n = n.nextSibling; } if (opt) { var _opt = opt.substr(1); var b = [];//定義一個數組,用於儲存過濾a的陣列 if (opt[0] === '.') { b = a.filter(function (item) { return item.className === _opt }); } else if (opt[0] === '#') { b = a.filter(function (item) { return item.id === _opt }); } else { b = a.filter(function (item) { return item.tagName.toLowerCase() === opt }); } return b; } return a; }, //設定樣式 css: function (obj, json) { for (var attr in json) { obj.style[attr] = json[attr]; } }, //設定HTML內容 html: function (obj) { if (arguments.length === 1) { return obj.innerHTML; } else if (arguments.length === 2) { obj.innerHTML = arguments[1]; } }, //設定HTML內容 text: function (obj) { if (arguments.length === 1) { return obj.innerHTML; } else if (arguments.length === 2) { obj.innerHTML = this.filterStr(arguments[1],'html'); } }, //顯示隱藏 show: function (obj) { var blockArr=['div','li','ul','ol','dl','table','article','h1','h2','h3','h4','h5','h6','p','hr','header','footer','details','summary','section','aside',''] if(blockArr.indexOf(obj.tagName.toLocaleLowerCase())===-1){ obj.style.display ='inline'; } else{ obj.style.display ='block'; } }, hide: function (obj) { obj.style.display = "none"; }, /* 封裝ajax函式 * @param {string}obj.type http連線的方式,包括POST和GET兩種方式 * @param {string}obj.url 傳送請求的url * @param {boolean}obj.async 是否為非同步請求,true為非同步的,false為同步的 * @param {object}obj.data 傳送的引數,格式為物件型別 * @param {function}obj.success ajax傳送並接收成功呼叫的回撥函式 * @param {function}obj.error ajax傳送失敗或者接收失敗呼叫的回撥函式 */ // ajax({ // type:'get', // url:'xxx', // data:{ // id:'111' // }, // success:function(res){ // console.log(res) // } // }) ajax: function (obj) { obj = obj || {}; obj.type = obj.type.toUpperCase() || 'POST'; obj.url = obj.url || ''; obj.async = obj.async || true; obj.data = obj.data || null; obj.success = obj.success || function () { }; obj.error = obj.error || function () { }; var xmlHttp = null; if (XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } else { xmlHttp = new ActiveXObject('Microsoft.XMLHTTP'); } var params = []; for (var key in obj.data) { params.push(key + '=' + obj.data[key]); } var postData = params.join('&'); if (obj.type.toUpperCase() === 'POST') { xmlHttp.open(obj.type, obj.url, obj.async); xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8'); xmlHttp.send(postData); } else if (obj.type.toUpperCase() === 'GET') { xmlHttp.open(obj.type, obj.url + '?' + postData, obj.async); xmlHttp.send(null); } xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { obj.success(xmlHttp.responseText); } else { obj.error(xmlHttp.responseText); } }; }, //圖片沒加載出來時用一張圖片代替 aftLoadImg: function (obj, url, errorUrl,cb) { var oImg = new Image(), _this = this; oImg.src = url; oImg.onload = function () { obj.src = oImg.src; if (cb && _this.istype(cb, 'function')) { cb(obj); } } oImg.onerror=function () { obj.src=errorUrl; if (cb && _this.istype(cb, 'function')) { cb(obj); } } }, //圖片滾動懶載入 //@className {string} 要遍歷圖片的類名 //@num {number} 距離多少的時候開始載入 預設 0 //比如,一張圖片距離文件頂部3000,num引數設定200,那麼在頁面滾動到2800的時候,圖片載入。不傳num引數就滾動,num預設是0,頁面滾動到3000就載入 //html程式碼 //<p><img data-src="lawyerOtherImg.jpg" class="load-img" width='528' height='304' /></p> //<p><img data-src="lawyerOtherImg.jpg" class="load-img" width='528' height='304' /></p> //<p><img data-src="lawyerOtherImg.jpg" class="load-img" width='528' height='304' /></p>.... //data-src儲存src的資料,到需要載入的時候把data-src的值賦值給src屬性,圖片就會載入。 //詳細可以檢視testLoadImg.html //window.onload = function() { // loadImg('load-img',100); // window.onscroll = function() { // loadImg('load-img',100); // } //} loadImg: function (className, num, errorUrl) { var _className = className || 'ec-load-img', _num = num || 0, _this = this,_errorUrl=errorUrl||null; var oImgLoad = document.getElementsByClassName(_className); for (var i = 0, len = oImgLoad.length; i < len; i++) { //如果圖片已經滾動到指定的高度 if (document.documentElement.clientHeight + document.documentElement.scrollTop > oImgLoad[i].offsetTop - _num && !oImgLoad[i].isLoad) { //記錄圖片是否已經載入 oImgLoad[i].isLoad = true; //設定過渡,當圖片下來的時候有一個圖片透明度變化 oImgLoad[i].style.cssText = "transition: ''; opacity: 0;" if (oImgLoad[i].dataset) { this.aftLoadImg(oImgLoad[i], oImgLoad[i].dataset.src, _errorUrl, function (o) { //新增定時器,確保圖片已經載入完了,再把圖片指定的的class,清掉,避免重複編輯 setTimeout(function () { if (o.isLoad) { _this.removeClass(o, _className); o.style.cssText = ""; } }, 1000) }); } else { this.aftLoadImg(oImgLoad[i], oImgLoad[i].getAttribute("data-src"), _errorUrl, function (o) { //新增定時器,確保圖片已經載入完了,再把圖片指定的的class,清掉,避免重複編輯 setTimeout(function () { if (o.isLoad) { _this.removeClass(o, _className); o.style.cssText = ""; } }, 1000) }); } (function (i) { setTimeout(function () { oImgLoad[i].style.cssText = "transition:all 1s; opacity: 1;"; }, 16) })(i); } } }, //建立正則字元 createKeyExp: function (strArr) { var str = ""; for (var i = 0; i < strArr.length; i++) { if (i != strArr.length - 1) { str = str + strArr[i] + "|"; } else { str = str + strArr[i]; } } return "(" + str + ")"; }, //關鍵字加標籤(多個關鍵詞用空格隔開) //ecDo.findKey('守侯我oaks接到了來自下次你離開快樂吉祥留在開城侯','守侯 開','i') //"<i>守侯</i>我oaks接到了來自下次你離<i>開</i>快樂吉祥留在<i>開</i>城侯" findKey: function (str, key, el) { var arr = null, regStr = null, content = null, Reg = null, _el = el || 'span'; arr = key.split(/\s+/); //alert(regStr); // 如:(前端|過來) regStr = this.createKeyExp(arr); content = str; //alert(Reg);// /如:(前端|過來)/g Reg = new RegExp(regStr, "g"); //過濾html標籤 替換標籤,往關鍵字前後加上標籤 content = content.replace(/<\/?[^>]*>/g, '') return content.replace(Reg, "<" + _el + ">$1</" + _el + ">"); }, //資料型別判斷 //ecDo.istype([],'array') //true //ecDo.istype([]) //'[object Array]' istype: function (o, type) { if (type) { var _type = type.toLowerCase(); } switch (_type) { case 'string': return Object.prototype.toString.call(o) === '[object String]'; case 'number': return Object.prototype.toString.call(o) === '[object Number]'; case 'boolean': return Object.prototype.toString.call(o) === '[object Boolean]'; case 'undefined': return Object.prototype.toString.call(o) === '[object Undefined]'; case 'null': return Object.prototype.toString.call(o) === '[object Null]'; case 'function': return Object.prototype.toString.call(o) === '[object Function]'; case 'array': return Object.prototype.toString.call(o) === '[object Array]'; case 'object': return Object.prototype.toString.call(o) === '[object Object]'; case 'nan': return isNaN(o); case 'elements': return Object.prototype.toString.call(o).indexOf('HTML') !== -1 default: return Object.prototype.toString.call(o) } }, //手機型別判斷 browserInfo: function (type) { switch (type) { case 'android': return navigator.userAgent.toLowerCase().indexOf('android') !== -1 case 'iphone': return navigator.userAgent.toLowerCase().indexOf('iphone') !== -1 case 'ipad': return navigator.userAgent.toLowerCase().indexOf('ipad') !== -1 case 'weixin': return navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1 default: return navigator.userAgent.toLowerCase() } }, //函式節流 // var count=0; // function fn1(){ // count++; // console.log(count) // } // //100ms內連續觸發的呼叫,後一個呼叫會把前一個呼叫的等待處理掉,但每隔200ms至少執行一次 // document.onmousemove=delayFn(fn1,100,200) delayFn: function (fn, delay, mustDelay) { var timer = null; var t_start; return function () { var context = this, args = arguments, t_cur = +new Date(); //先清理上一次的呼叫觸發(上一次呼叫觸發事件不執行) clearTimeout(timer); //如果不存觸發時間,那麼當前的時間就是觸發時間 if (!t_start) { t_start = t_cur; } //如果當前時間-觸發時間大於最大的間隔時間(mustDelay),觸發一次函式執行函式 if (t_cur - t_start >= mustDelay) { fn.apply(context, args); t_start = t_cur; } //否則延遲執行 else { timer = setTimeout(function () { fn.apply(context, args); }, delay); } }; } }
/*2.0.0*/
var utils = {
//***************字串模組**************************/
//去除空格 type 1-所有空格 2-前後空格 3-前空格 4-後空格
//trim(' 1235asd',1)
//result:1235asd
trim(str, type) {
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;
}
},
/*type
1:首字母大寫
2:首字母小寫
3:大小寫轉換
4:全部大寫
5:全部小寫
* */
//changeCase('asdasd',1)
//result:Asdasd
changeCase(str, type) {
function ToggleCase(str) {
let itemText = ""
str.split("").forEach(item => {
if (/^([a-z]+)/.test(item)) {
itemText += item.toUpperCase();
} else if (/^([A-Z]+)/.test(item)) {
itemText += item.toLowerCase();
} else {
itemText += item;
}
});
return itemText;
}
switch (type) {
case 1:
return str.replace(/\b\w+\b/g, function (word) {
return word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase();
});
case 2:
return str.replace(/\b\w+\b/g, function (word) {
return word.substring(0, 1).toLowerCase() + word.substring(1).toUpperCase();
});
case 3:
return ToggleCase(str);
case 4:
return str.toUpperCase();
case 5:
return str.toLowerCase();
default:
return str;
}
},
//字串迴圈複製
//repeatStr(str->字串, count->次數)
//repeatStr('123',3)
//"result:123123123"
repeatStr(str, count) {
return str.repeat(count);
},
//字串替換(字串,要替換的字元或者正則表示式(不要寫g),替換成什麼)
//ecDo.replaceAll('這裡是上海,中國第三大城市,廣東省省會,簡稱穗,','上海','廣州')
//result:"這裡是廣州,中國第三大城市,廣東省省會,簡稱穗,"
replaceAll(str, AFindText, ARepText) {
let raRegExp = new RegExp(AFindText, "g");
return str.replace(raRegExp, ARepText);
},
//字元替換*
//replaceStr(字串,字元格式, 替換方式,替換的字元(預設*))
replaceStr(str, regArr, type = 0, ARepText = '*') {
let regtext = '',
Reg = null,
replaceText = ARepText;
//replaceStr('18819322663',[3,5,3],0)
//result:188*****663
//repeatStr是在上面定義過的(字串迴圈複製),大家注意哦
if (regArr.length === 3 && type === 0) {
regtext = '(\\w{' + regArr[0] + '})\\w{' + regArr[1] + '}(\\w{' + regArr[2] + '})'
Reg = new RegExp(regtext);
let replaceCount = this.repeatStr(replaceText, regArr[1]);
return str.replace(Reg, '$1' + replaceCount + '$2')
}
//replaceStr('asdasdasdaa',[3,5,3],1)
//result:***asdas***
else if (regArr.length === 3 && type === 1) {
regtext = '\\w{' + regArr[0] + '}(\\w{' + regArr[1] + '})\\w{' + regArr[2] + '}'
Reg = new RegExp(regtext);
let replaceCount1 = this.repeatStr(replaceText, regArr[0]);
let replaceCount2 = this.repeatStr(replaceText, regArr[2]);
return str.replace(Reg, replaceCount1 + '$1' + replaceCount2)
}
//replaceStr('1asd88465asdwqe3',[5],0)
//result:*****8465asdwqe3
else if (regArr.length === 1 && type === 0) {
regtext = '(^\\w{' + regArr[0] + '})'
Reg = new RegExp(regtext);
let replaceCount = this.repeatStr(replaceText, regArr[0]);
return str.replace(Reg, replaceCount)
}
//replaceStr('1asd88465asdwqe3',[5],1,'+')
//result:"1asd88465as+++++"
else if (regArr.length === 1 && type === 1) {
regtext = '(\\w{' + regArr[0] + '}$)'
Reg = new RegExp(regtext);
let replaceCount = this.repeatStr(replaceText, regArr[0]);
return str.replace(Reg, replaceCount)
}
},
//檢測字串
//checkType('165226226326','phone')
//result:false
//大家可以根據需要擴充套件
checkType(str, type) {
switch (type) {
case 'email':
return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
case 'phone':
return /^1[3|4|5|7|8][0-9]{9}$/.test(str);
case 'tel':
return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);
case 'number':
return /^[0-9]$/.test(str);
case 'english':
return /^[a-zA-Z]+$/.test(str);
case 'text':
return /^\w+$/.test(str);
case 'chinese':
return /^[\u4E00-\u9FA5]+$/.test(str);
case 'lower':
return /^[a-z]+$/.test(str);
case 'upper':
return /^[A-Z]+$/.test(str);
default:
return true;
}
},
//檢測密碼強度
//checkPwd('12asdASAD')
//result:3(強度等級為3)
checkPwd(str) {
let nowLv = 0;
if (str.length < 6) {
return nowLv
}
if (/[0-9]/.test(str)) {
nowLv++
}
if (/[a-z]/.test(str)) {
nowLv++
}
if (/[A-Z]/.test(str)) {
nowLv++
}
if (/[\.|-|_]/.test(str)) {
nowLv++
}
return nowLv;
},
//隨機碼
//count取值範圍2-36
//randomWord(10)
//result:"2584316588472575"
//randomWord(14)
//result:"9b405070dd00122640c192caab84537"
//randomWord(36)
//result:"83vhdx10rmjkyb9"
randomWord(count) {
return Math.random().toString(count).substring(2);
},
//查詢字串
//let strTest='sad44654blog5a1sd67as9dablog4s5d16zxc4sdweasjkblogwqepaskdkblogahseiuadbhjcibloguyeajzxkcabloguyiwezxc967'
//countStr(strTest,'blog')
//result:6
countStr(str, strSplit) {
return str.split(strSplit).length - 1
},
//過濾字串(html標籤,表情,特殊字元)
//字串,替換內容(special-特殊字元,html-html標籤,emjoy-emjoy表情,word-小寫字母,WORD-大寫字母,number-數字,chinese-中文),要替換成什麼,預設'',保留哪些特殊字元
//如果需要過濾多種字元,type引數使用,分割,如下栗子
//過濾字串的html標籤,大寫字母,中文,特殊字元,全部替換成*,但是特殊字元'%','?',除了這兩個,其他特殊字元全部清除
//let str='asd 654a大蠢sasdasdASDQWEXZC6d5#%^*^&*^%^&*$\\"\'#@!()*/-())_\'":"{}?<div></div><img src=""/>啊實打實大蠢豬自行車這些課程';
// ecDo.filterStr(str,'html,WORD,chinese,special','*','%?')
//result:"asd 654a**sasdasd*********6d5#%^*^&*^%^&*$\"'#@!()*/-())_'":"{}?*****************"
filterStr(str, type, restr = '', spstr) {
let typeArr = type.split(','), _str = str;
for (let i = 0, len = typeArr.length; i < len; i++) {
//是否是過濾特殊符號
let pattern;
if (typeArr[i] === 'special') {
let regText = '$()[]{}?\|^*+./\"\'+';
//是否有哪些特殊符號需要保留
if (spstr) {
let _spstr = spstr.split(""), _regText = "[^0-9A-Za-z\\s";
for (let j = 0, len1 = _spstr.length; j < len1; j++) {
if (regText.indexOf(_spstr[j]) === -1) {
_regText += _spstr[j];
}
else {
_regText += '\\' + _spstr[j];
}
}
_regText += ']'
pattern = new RegExp(_regText, 'g');
}
else {
pattern = new RegExp("[^0-9A-Za-z\\s]", 'g')
}
}
switch (typeArr[i]) {
case 'special':
_str = _str.replace(pattern, restr);
break;
case 'html':
_str = _str.replace(/<\/?[^>]*>/g, restr);
break;
case 'emjoy':
_str = _str.replace(/[^\u4e00-\u9fa5|\u0000-\u00ff|\u3002|\uFF1F|\uFF01|\uff0c|\u3001|\uff1b|\uff1a|\u3008-\u300f|\u2018|\u2019|\u201c|\u201d|\uff08|\uff09|\u2014|\u2026|\u2013|\uff0e]/g, restr);
break;
case 'word':
_str = _str.replace(/[a-z]/g, restr);
break;
case 'WORD':
_str = _str.replace(/[A-Z]/g, restr);
break;
case 'number':
_str = _str.replace(/[0-9]/g, restr);
break;
case 'chinese':
_str = _str.replace(/[\u4E00-\u9FA5]/g, restr);
break;
}
}
return _str;
},
//格式化處理字串
//ecDo.formatText('1234asda567asd890')
//result:"12,34a,sda,567,asd,890"
//ecDo.formatText('1234asda567asd890',4,' ')
//result:"1 234a sda5 67as d890"
//ecDo.formatText('1234asda567asd890',4,'-')
//result:"1-234a-sda5-67as-d890"
formatText(str, size = 3, delimiter = ',') {
let regText = '\\B(?=(\\w{' + size + '})+(?!\\w))';
let reg = new RegExp(regText, 'g');
return str.replace(reg, delimiter);
},
//找出最長單詞 (Find the Longest word in a String)
//longestWord('Find the Longest word in a String')
//result:7
//longestWord('Find|the|Longest|word|in|a|String','|')
//result:7
longestWord(str, splitType = /\s+/g) {
let _max = 0, _item = '';
let strArr = str.split(splitType);
strArr.forEach(item => {
if (_max < item.length) {
_max = item.length;
_item = item;
}
});
return {el: _item, max: _max};
},
//句中單詞首字母大寫 (Title Case a Sentence)
//這個我也一直在糾結,英文標題,即使是首字母大寫,也未必每一個單詞的首字母都是大寫的,但是又不知道哪些應該大寫,哪些不應該大寫
//ecDo.titleCaseUp('this is a title')
//"This Is A Title"
titleCaseUp(str, splitType = /\s+/g) {
let strArr = str.split(splitType),
result = "";
strArr.forEach(item => {
result += this.changeCase(item, 1) + ' ';
});
return this.trim(result, 4)
},
//***************字串模組End**************************/
//***************陣列模組**************************/
//陣列去重
removeRepeatArray(arr) {
// return arr.filter(function (item, index, self) {
// return self.indexOf(item) === index;
// });
//es6
return [...new Set(arr)]
},
//陣列順序打亂
upsetArr(arr) {
return arr.sort(() => {
return Math.random() - 0.5
});
},
//陣列最大值
//這一塊的封裝,主要是針對數字型別的陣列
maxArr(arr) {
return Math.max.apply(null, arr);
},
//陣列最小值
minArr(arr) {
return Math.min.apply(null, arr);
},
//這一塊的封裝,主要是針對數字型別的陣列
//陣列求和
sumArr(arr) {
return arr.reduce((pre, cur) =>pre + cur)
},
//陣列平均值,小數點可能會有很多位,這裡不做處理,處理了使用就不靈活了!
covArr(arr) {
return this.sumArr(arr) / arr.length;
},
//從陣列中隨機獲取元素
randomOne(arr) {
return arr[Math.floor(Math.random() * arr.length)];
},
//回陣列(字串)一個元素出現的次數
//getEleCount('asd56+asdasdwqe','a')
//result:3
//getEleCount([1,2,3,4,5,66,77,22,55,22],22)
//result:2
getEleCount(obj, ele) {
let num = 0;
for (let i = 0, len = obj.length; i < len; i++) {
if (ele === obj[i]) {
num++;
}
}
return num;
},
//返回陣列(字串)出現最多的幾次元素和出現次數
//arr, rank->長度,預設為陣列長度,ranktype,排序方式,預設降序
//返回值:el->元素,count->次數
//getCount([1,2,3,1,2,5,2,4,1,2,6,2,1,3,2])
//result:[{"el":"2","count":6},{"el":"1","count":4},{"el":"3","count":2},{"el":"4","count":1},{"el":"5","count":1},{"el":"6","count":1}]
//預設情況,返回所有元素出現的次數
//getCount([1,2,3,1,2,5,2,4,1,2,6,2,1,3,2],3)
//傳參(rank=3),只返回出現次數排序前三的
//result:[{"el":"2","count":6},{"el":"1","count":4},{"el":"3","count":2}]
//getCount([1,2,3,1,2,5,2,4,1,2,6,2,1,3,2],null,1)
//傳參(ranktype=1,rank=null),升序返回所有元素出現次數
//result:[{"el":"6","count":1},{"el":"5","count":1},{"el":"4","count":1},{"el":"3","count":2},{"el":"1","count":4},{"el":"2","count":6}]
//getCount([1,2,3,1,2,5,2,4,1,2,6,2,1,3,2],3,1)
//傳參(rank=3,ranktype=1),只返回出現次數排序(升序)前三的
//result:[{"el":"6","count":1},{"el":"5","count":1},{"el":"4","count":1}]
getCount(arr, rank, ranktype) {
let obj = {}, k, arr1 = []
//記錄每一元素出現的次數
for (let i = 0, len = arr.length; i < len; i++) {
k = arr[i];
if (obj[k]) {
obj[k]++;
} else {
obj[k] = 1;
}
}
//儲存結果{el-'元素',count-出現次數}
for (let o in obj) {
arr1.push({el: o, count: obj[o]});
}
//排序(降序)
arr1.sort(function (n1, n2) {
return n2.count - n1.count
});
//如果ranktype為1,則為升序,反轉陣列
if (ranktype === 1) {
arr1 = arr1.reverse();
}
let rank1 = rank || arr1.length;
return arr1.slice(0, rank1);
},
//得到n1-n2下標的陣列
//getArrayNum([0,1,2,3,4,5,6,7,8,9],5,9)
//result:[5, 6, 7, 8, 9]
//getArrayNum([0,1,2,3,4,5,6,7,8,9],2) 不傳第二個引數,預設返回從n1到陣列結束的元素
//result:[2, 3, 4, 5, 6, 7, 8, 9]
getArrayNum(arr, n1, n2) {
return arr.slice(n1, n2);
},
//篩選陣列
//刪除值為'val'的陣列元素
//removeArrayForValue(['test','test1','test2','test','aaa'],'test','%')
//result:["aaa"] 帶有'test'的都刪除
//removeArrayForValue(['test','test1','test2','test','aaa'],'test')
//result:["test1", "test2", "aaa"] //陣列元素的值全等於'test'才被刪除
removeArrayForValue(arr, val, type) {
return arr.filter(item=>type ? item.indexOf(val) === -1 : item !== val)
},
//獲取物件陣列某些項
//let arr=[{a:1,b:2,c:9},{a:2,b:3,c:5},{a:5,b:9},{a:4,b:2,c:5},{a:4,b:5,c:7}]
//getOptionArray(arr,'a,c')
//result:[{a:1,c:9},{a:2,c:5},{a:5,c:underfind},{a:4,c:5},{a:4,c:7}]
//getOptionArray(arr,'b',1)
//result:[2, 3, 9, 2, 5]
getOptionArray(arr, keys) {
let newArr = [];
if (!keys) {
return arr
}
let _keys = keys.split(','), newArrOne = {};
//是否只是需要獲取某一項的值
if (_keys.length === 1) {
for (let i = 0, len = arr.length; i < len; i++) {
newArr.push(arr[i][keys])
}
return newArr;
}
for (let i = 0, len = arr.length; i < len; i++) {
newArrOne = {};
for (let j = 0, len1 = _keys.length; j < len1; j++) {
newArrOne[_keys[j]] = arr[i][_keys[j]]
}
newArr.push(newArrOne);
}
return newArr
},
//排除陣列某些項
//let arr=[{a:1,b:2,c:9},{a:2,b:3,c:5},{a:5,b:9},{a:4,b:2,c:5},{a:4,b:5,c:7}]
//filterOptionArray(arr,'a')
//result:[{b:2,c:9},{b:3,c:5},{b:9},{b:2,c:5},{b:5,c:7}]
//filterOptionArray(arr,'a,c')
//result:[{b:2},{b:3},{b:9},{b:2},{b:5}]
filterOptionArray(arr, keys) {
let newArr = [];
let _keys = keys.split(','), newArrOne = {};
for (let i = 0, len = arr.length; i < len; i++) {
newArrOne = {};
for (let key in arr[i]) {
//如果key不存在排除keys裡面,新增資料
if (_keys.indexOf(key) === -1) {
newArrOne[key] = arr[i][key];
}
}
newArr.push(newArrOne);
}
return newArr
},
//物件陣列的排序
//let arr=[{a:1,b:2,c:9},{a:2,b:3,c:5},{a:5,b:9},{a:4,b:2,c:5},{a:4,b:5,c:7}]
//ecDo.arraySort(arr,'a,b')a是第一排序條件,b是第二排序條件
//result:[{"a":1,"b":2,"c":9},{"a":2,"b":3,"c":5},{"a":4,"b":2,"c":5},{"a":4,"b":5,"c":7},{"a":5,"b":9}]
arraySort(arr, sortText) {
if (!sortText) {
return arr
}
let _sortText = sortText.split(',').reverse(), _arr = arr.slice(0);
for (let i = 0, len = _sortText.length; i < len; i++) {
_arr.sort((n1, n2) => {
return n1[_sortText[i]] - n2[_sortText[i]]
})
}
return _arr;
},
//陣列扁平化
steamroller(arr) {
let newArr = [], _this = this;
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
// 如果是陣列,呼叫(遞迴)steamroller 將其扁平化
// 然後再 push 到 newArr 中
newArr.push.apply(newArr, _this.steamroller(arr[i]));
} else {
// 不是陣列直接 push 到 newArr 中
newArr.push(arr[i]);
}
}
return newArr;
},
//另一種寫法
//steamroller([1,2,[4,5,[1,23]]])
//[1, 2, 4, 5, 1, 23]
/*
* i=0 newArr.push(arr[i]) [1]
* i=1 newArr.push(arr[i]) [1,2]
* i=2 newArr = newArr.concat(steamroller(arr[i])); 執行到下面
* 第一次i=2進入後 i=0, newArr.push(arr[i]); [4]
* 第一次i=2進入後 i=1, newArr.push(arr[i]); [4,5]
* * i=2 newArr = newArr.concat(steamroller(arr[i])); 執行到下面
* 第二次i=2進入後 i=0, newArr.push(arr[i]); [1]
* 第二次i=2進入後 i=1, newArr.push(arr[i]); [1,23] 執行到下面
* 第二次迴圈完,回到第一次進入後 newArr = newArr.concat(steamroller(arr[i])); [4,5].concat([1,23]) [4,5,1,23]
* 然後回到第一次 [1,2].concat([4,5,1,23])
*/
// steamroller(arr) {
// let newArr = [];
// for (let i = 0; i < arr.length; i++) {
// if (Array.isArray(arr[i])) {
// // 如果是陣列,呼叫(遞迴)steamroller 將其扁平化
// // 然後再 push 到 newArr 中
// newArr = newArr.concat(steamroller(arr[i]));
// } else {
// // 不是陣列直接 push 到 newArr 中
// newArr.push(arr[i]);
// }
// }
// return newArr;
// },
//***************陣列模組END**************************/
//***************物件及其他模組**************************/
//適配rem
getFontSize(_client) {
let doc = document,
win = window;
let docEl = doc.documentElement,
resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
recalc = function () {
let clientWidth = docEl.clientWidth;
if (!clientWidth) return;
//如果螢幕大於750(750是根據我效果圖設定的,具體數值參考效果圖),就設定clientWidth=750,防止font-size會超過100px
if (clientWidth > _client) {
clientWidth = _client
}
//設定根元素font-size大小
docEl.style.fontSize = 100 * (clientWidth / _client) + 'px';
};
//螢幕大小改變,或者橫豎屏切換時,觸發函式
win.addEventListener(resizeEvt, recalc, false);
//文件載入完成時,觸發函式
doc.addEventListener('DOMContentLoaded', recalc, false);
},
//到某一個時間的倒計時
//getEndTime('2017/7/22 16:0:0')
//result:"剩餘時間6天 2小時 28 分鐘20 秒"
getEndTime(endTime) {
let startDate = new Date(); //開始時間,當前時間
let endDate = new Date(endTime); //結束時間,需傳入時間引數
let t = endDate.getTime() - startDate.getTime(); //時間差的毫秒數
let d = 0,
h = 0,
m = 0,
s = 0;
if (t >= 0) {
d = Math.floor(t / 1000 / 3600 / 24);
h