日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

JavaScript常用工具类整理(总结版)

發布時間:2023/12/2 javascript 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JavaScript常用工具类整理(总结版) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

導讀:在前端開發過程中需要對常用的功能模塊進行封裝,常用的方法多次調用需要整合,保證組件的復用性與程序的可維護性,這里總結一下,便于后續的使用!

?

目錄

1.全局聲明工具類

2.定時器

3.判斷變量是否是一個值

4.判斷變量是否為空

5.判斷變量是否為一個數組

6.輸入對象

7.將object對象轉化為數組

8.對象轉字符串

9.json字符串轉json對象

10.判斷是否為數字

11.判斷是否為整型

12.判斷是否為浮點型

13.手機號驗證

14.文本輸入校驗(中文、數字、字母、下劃線、中文標點符號。?;??,?:?“?”(?)?、???《?》)

15.左填充(str?原字符串,len?目標長度,pad?填充的字符(默認:空格))

16.右填充

17.消除空格

18.json對象轉form數據

19.IP有效驗證

20.ASCII轉HEX

21.HEX轉ASCII

22.金額自動加","分割(v_money?要格式化的金額,need_dot?是否需要精確到小數點后2位,{String}?格式化以后的金額,如:1,234,567.08)

?23.把金額數字轉換為中文大寫金額

24.生成驗證碼(len?驗證碼長度(默認:6),{String}?生成的驗證碼,)

25.格式化賬號顯示(4位加空格)

26.格式化戶名顯示,2字屏蔽第1位,用*號代替,3字屏蔽第2位,用*號代替,3字以上,顯示第1位和最后1位,其余用*號代替,最多使用5位*。

27.字符串替換

28.生成UUID(len?UUID長度,默認標準36位,radix?UUID基數,默認16)

29.隨機數生成36位UUID

30.解析json,結果返回

31.金額數據分轉元

32.金額數據元轉分

33.兩個浮點型相減,不丟失精度

34.?兩個浮點型相加,不丟失精度

35.按長度數組截取字符串,返回按長度分割成的字符串數組

36.按多長間隔截取字符串,n為長度,返回按長度分割成的字符串數組

37.格式化字符串

38.存期格式化

39.計算總頁數,根據總條數和每頁顯示數(totalpage:總條數,pagesize:每頁顯示條數)

?40.將‘YYYYMMDD’格式的字符串格式化成‘YYYY-MM-DD’的格式

41.理財,將幣種(數字)轉為漢字

42.H5獲取自己本地IP地址

43.通過http請求獲取文本數據

44.數組轉對象

45.精準乘法

46.判斷當前瀏覽器環境

47.?播放語音(src?語音文件url)

48.檢測操作系統版本號(Mac?|?Unix?|?Android?|?Linux?|?Win2000?|?WinXP?|?Win2003?|?WinVistta?|?Win7?|?Win10?|?Volcano?|?other)

49.判斷應用部署模式(CS?|?BS)

50.獲取JS字符串字節數,str?要計算的字符串(str的字節數,中文占2個字節,英文占1個字節)

51.格式化手機號(11位手機號)

52.左補兩位

53.hex?->?dsp(hex?十六進制壓縮碼?如[0x12,?0x34,?0x56],?dsp?如?"123456")

54.dsp?->?hex?

55.分量亦或合成(itemA?分量A,itemB?分量B,bDsp?是否擴展?true,則傳入的itemA與itemB與返回的合成變量都為擴展碼,否則都為Uint8Array類型的壓縮碼數組)


?

1.全局聲明工具類

window.$App = window.$App || {};window.$App.AppUtils = (function () {let apputils = {}; }

2.定時器

/*** 定時器* @class Timer */apputils.Timer = ClassLoader.create();apputils.Timer.prototype = {initialize: function ($, A, _) {this._h = null;this.callback = $;this.interval = A;this.loop = _ ? true : false;this.running = false},onTimer: function () {if (!this.running) {try {this.running = true;this.callback();} finally {this.running = false;}}if (this.loop == false) {this.stop();}},stop: function () {clearInterval(this._h);},start: function () {this.stop();this._h = setInterval(this.onTimer.bind(this), this.interval * 1000);}};/*** 啟動定時器* @param {*} times 倒計時時間,單位:秒* @param {*} callback 倒計時完成回調函數* @param {*} repeat 是否循環執行* @returns {object} 定時器對象,支持方法:start、stop* @function startTimer*/apputils.startTimer = function (times, callback, repeat) {try {var timer = new this.Timer(function () {callback();}, times, repeat);timer.start();return timer;} catch (ajaxException) {alert(ajaxException.message);}return null;};

3.判斷變量是否是一個值

function (o) {return typeof (o) !== 'undefined' && o !== null ? true : false;};

4.判斷變量是否為空

function (val) {var regu = "^[ ]+$";var re = new RegExp(regu);return val == null || typeof (val) == 'undefined' || val == "" || re.test(val);};

5.判斷變量是否為一個數組

function (o) {return this.isvalue(o) ? Object.prototype.toString.apply(o) === '[object Array]' :false;};

6.輸入對象

function (o) {return this.isarray(o) ? o.length : -1;};

7.將object對象轉化為數組

function (o) {return this.isarray(o) ? o : new Array();};

8.對象轉字符串

function (o) {var str = "";if (this.isvalue(o)) {var t = Object.prototype.toString.apply(o);if (t === '[object Array]') {let a = [];for (var i = 0; i < o.length; i++) {/*** 此處原方法為a.push(this.tostring(o[i]));* 當o為字符串數組是,返回的結果出錯,因此做了如下修改*/if (this.tostring(o[i]).charAt(0) == '{') { //o為json數組時a.push(this.tostring(o[i]));} else { //o為字符串數組時a.push('"' + this.tostring(o[i]) + '"');}}str = '[' + a.join(',') + ']';a.length = 0;// a = null;} else if (t === '[object Date]') {var y = o.getFullYear();if (y < 1900) {y += 1900;}var m = o.getMonth() + 1;str = y + "-" + this.lpad(m, 2, '0') + "-" +this.lpad(o.getDate(), 2, '0') + " " +this.lpad(o.getHours(), 2, '0') + ":" +this.lpad(o.getMinutes(), 2, '0') + ":" +this.lpad(o.getSeconds(), 2, '0');} else if (t === '[object Object]') {let a = [],k;for (k in o) {var vt = Object.prototype.toString.apply(o[k]);if (vt === '[object Array]' || vt === '[object Object]') {a.push('"' + k + '":' + this.tostring(o[k]));} else {a.push('"' + k + '":"' + this.tostring(o[k]) + '"');}}str = '{' + a.join(',') + '}';a.length = 0;// a = null;} else {str = String(o);}}return str;};

9.json字符串轉json對象

function (str) {if (str == null || str == "") {return "";}if (str.charAt(0) != '(') {str = "(" + str + ")";}return eval(str);};

10.判斷是否為數字

function (str) {var regu = /^(\d+)$/;return regu.test(str);};

11.判斷是否為整型

function (str) {var regu = /^[-]{0,1}[0-9]{1,}$/;return regu.test(this.val(str));};

12.判斷是否為浮點型

function (str) {if (this.isint(str))return true;var re = /^[-]{0,1}(\d+)[.]+(\d+)$/;if (re.test(str)) {if (RegExp.$1 == 0 && RegExp.$2 == 0)return false;return true;} else {return false;}};

13.手機號驗證

function (s) {var patrn = /^(13[0-9]|14[0-9]|15[0-9]|17[0-9]|18[0-9])\d{8}$/;return patrn.exec(s);};

14.文本輸入校驗(中文、數字、字母、下劃線、中文標點符號。?;??,?:?“?”(?)?、???《?》)

function (s) {var patrn = /^[\u4e00-\u9fa5_a-zA-Z0-9_\u3002\uff1b\uff0c\uff1a\u201c\u201d\uff08\uff09\u3001\uff1f\u300a\u300b]*$/;return patrn.exec(s);};

15.左填充(str?原字符串,len?目標長度,pad?填充的字符(默認:空格))

function (str, len, pad) {str = this.tostring(str);if (typeof (len) === "undefined") {len = 0;}if (typeof (pad) === "undefined") {pad = ' ';}if (len + 1 >= str.length) {str = Array(len + 1 - str.length).join(pad) + str;}return str;};

16.右填充

function (str, len, pad) {str = this.tostring(str);if (typeof (len) === "undefined") {len = 0;}if (typeof (pad) === "undefined") {pad = ' ';}if (len + 1 >= str.length) {str = str + Array(len + 1 - str.length).join(pad);}return str;};

17.消除空格

function (text) {return (text || "").replace(/^\s+|\s+$/g, "");};

18.json對象轉form數據

function (json) {var str = "";for (var i in json) {str += "&" + i + "=" + json[i];}if (str.length > 1) {str = str.substring(1);}return str;};

19.IP有效驗證

function (ip) {var re = /(\d+)\.(\d+)\.(\d+)\.(\d+)/g; //匹配IP地址的正則表達式if (re.test(ip)) {var arr = ip.split(".");if (arr[0] > 254 || arr[1] > 254 || arr[2] > 254 || arr[3] > 254)return false;return true;} else {return false;}}

20.ASCII轉HEX

function (str) {if (!this.isvalue(str)) {return "";}var hex = "";for (var i = 0; i < str.length; ++i) {hex += str.charCodeAt(i).toString(16);}return hex;}

21.HEX轉ASCII

function (hex) {if (!this.isvalue(hex) || hex.length % 2 != 0) {return "";}var str = "";for (var i = 0; i < hex.length / 2; ++i) {var tmp = "0x" + hex[i * 2] + hex[i * 2 + 1];var charValue = String.fromCharCode(Number(tmp));str += charValue;}return str;}

22.金額自動加","分割(v_money?要格式化的金額,need_dot?是否需要精確到小數點后2位,{String}?格式化以后的金額,如:1,234,567.08)

function (v_money, need_dot) {try {var p_number = parseFloat(v_money);if(isNaN(p_number)) {return v_money;}var p_string = "" + p_number;var p_idx = p_string.lastIndexOf(".");if (p_idx < 0) {p_idx = p_string.length;p_string = p_string + ".00";} else {var sarray = p_string.split('.');if (sarray[1] == '') {p_string = p_string + "00";} else if (sarray[1].length == 1) {p_string = p_string + "0";}}var p_ret = p_string.substring(p_idx);var p_temp = p_string.substring(0, p_idx);var p_length = p_temp.length;var p_count = Math.ceil(p_length / 3);for (var p_i = 0; p_i < p_count; p_i++) {var p_start_i = p_length - (p_i + 1) * 3;p_ret = p_temp.substring(p_start_i, p_start_i + 3) + p_ret;if (p_i < p_count - 1) {p_ret = "," + p_ret;}}if (need_dot == false) {var len = p_ret.indexOf(".");p_ret = p_ret.substring(0, len);}return p_ret;} catch (p_ee) {return "";}};

?23.把金額數字轉換為中文大寫金額

function (n) {var fraction = ['角', '分'];var digit = ['零', '壹', '貳', '叁', '肆', '伍', '陸', '柒', '捌', '玖'];var unit = [['元', '萬', '億'],['', '拾', '佰', '仟']];var head = n < 0 ? '欠' : '';n = Math.abs(n);var 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++) {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;}return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');};

24.生成驗證碼(len?驗證碼長度(默認:6),{String}?生成的驗證碼,)

function (len) {var charactors = "1234567890";var value = '';if (!this.isint(len)) {len = 6;}for (let j = 1; j <= len; j++) {var i = parseInt(10 * Math.random());value = value + charactors.charAt(i);}return value;};

25.格式化賬號顯示(4位加空格)

function (account) {if (!this.isvalue(account)) {return "";}if(account.startsWith("1")){if(account.length >= 17){account=account.substring(0,6)+"******"+account.substring(account.length-5);}}if(account.startsWith("6")){if(account.length >= 16){account=account.substring(0,4)+" **** **** "+account.substring(account.length-4);}}return account;};

26.格式化戶名顯示,2字屏蔽第1位,用*號代替,3字屏蔽第2位,用*號代替,3字以上,顯示第1位和最后1位,其余用*號代替,最多使用5位*。

function (name) {if (!this.isvalue(name)) {return "";}var res = "";if (name.length == 1) {res += name;}if (name.length == 2) {res += "*";res += name.substring(name.length - 1);}if (name.length == 3) {res += name.substring(0, 1);res += "*";res += name.substring(2);}if (name.length > 3) {res += name.substring(0, 1);for(let i=0; i<name.length - 2; i++) {if(i <= 4) {res += "*";} else {break;}}res += name.substring(name.length - 1, name.length);}return res;};

27.字符串替換

function (sourceString, startPos, encryptCount, encryptChar) {if (typeof sourceString != 'string')return sourceString;if (sourceString.length <= 0)return sourceString;if (typeof startPos != 'number')return sourceString;if (startPos <= 0)return sourceString;if (typeof encryptCount != 'number')return sourceString;if (encryptCount <= 0)return sourceString;if (startPos > sourceString.length)return sourceString;if ((startPos + encryptCount) > sourceString.length + 1)return sourceString;var str1 = sourceString.substr(0, startPos - 1);var str2 = sourceString.substr(startPos - 1, sourceString.length - startPos + 1);var str3 = '';var str4 = str2.substr(encryptCount, str2.length - encryptCount);for (var i = 0; i < encryptCount; i++) {str3 = str3 + encryptChar;}return str1 + str3 + str4;};

28.生成UUID(len?UUID長度,默認標準36位,radix?UUID基數,默認16)

function (len, radix) {var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');var uuid = [],i;radix = radix || chars.length;if (len) {// Compact formfor (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];} else {// rfc4122, version 4 formvar r;// rfc4122 requires these charactersuuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';uuid[14] = '4';// Fill in random data. At i==19 set the high bits of clock sequence as// per rfc4122, sec. 4.1.5for (i = 0; i < 36; i++) {if (!uuid[i]) {r = 0 | Math.random() * 16;uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];}}}return uuid.join('');};

29.隨機數生成36位UUID

function () {var s4 = function () {return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);}return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();};

30.解析json,結果返回

function (str) {if (typeof str == 'string') {try {var obj = JSON.parse(str);if (typeof obj == 'object' && obj) {return obj;} else {return false;}} catch (e) {return false;}} else if (typeof str == 'object') {console.log('It is a object already!');return str;}console.log('It is not a string!')};

31.金額數據分轉元

function (money) {if (typeof money == 'string') {money = money.split(".").join("");//去調小數點var money2 = parseInt(money);money2 = money2.toString();if (money2.length > 2) {money2 = money2.substring(0, money2.length - 2) + "." + money2.substring(money2.length - 2, money2.length);} else if (money2 == 0) {money2 = "0.00";} else if (money2.length == 2) {money2 = "0." + money2;} else if (money2.length == 1) {money2 = "0.0" + money2;}return money2;}console.log('It is not a string!')};

32.金額數據元轉分

function (money) {if (typeof money == 'string') {var money2 = money.replaceAll(",", "");if (money2.indexOf(".") < 0) {money2 = money2 + "00"} else if (money2.length - money2.indexOf(".") == 2) {//一位小數money2 = money2.replace(".", "") + '0';} else {//兩位小數money2 = money2.replace(".", "");}return money2;}console.log('It is not a string!')};

33.兩個浮點型相減,不丟失精度

function (arg1, arg2) {var r1, r2, m, n;try {r1 = arg1.toString().split(".")[1].length} catch (error) {r1 = 0}try {r2 = arg2.toString().split(".")[1].length} catch (error) {r2 = 0}m = Math.pow(10, Math.max(r1, r2));n = (r1 >= r2) ? r1 : r2;return ((arg1 * m - arg2 * m) / m).toFixed(n);};

34.?兩個浮點型相加,不丟失精度

function (arg1, arg2) {var r1, r2, m, n;try {r1 = arg1.toString().split(".")[1].length} catch (error) {r1 = 0}try {r2 = arg2.toString().split(".")[1].length} catch (error) {r2 = 0}m = Math.pow(10, Math.max(r1, r2));n = (r1 >= r2) ? r1 : r2;return ((arg1 * m + arg2 * m) / m).toFixed(n);};

35.按長度數組截取字符串,返回按長度分割成的字符串數組

function (str, lens) {var arr = [];var len = lens.length;for (var i = 0; i < len; i++) {if (str.length >= lens[i]) {var strCut = str.substring(0, lens[i]);arr.push(strCut);str = str.substring(lens[i]);} else {// str = str;arr.push(str);}}return arr;};

36.按多長間隔截取字符串,n為長度,返回按長度分割成的字符串數組

function (n) {var str = this;var arr = [];var len = Math.ceil(str.length / n);for (var i = 0; i < len; i++) {if (str.length >= n) {var strCut = str.substring(0, n);arr.push(strCut);str = str.substring(n);} else {// str = str;arr.push(str);}}return arr;};

37.格式化字符串

function (fmtStr, obj) {if (!fmtStr.formatStr) {String.prototype.formatStr = function (argsObj) {var regexp = /\{(\d+)\}/g;var args = argsObj || [];var result = this.replace(regexp, function (m, i, o, n) {// console.log(o + n)return args[i];});return result.replace('%', "'");};}return fmtStr.formatStr(obj);};

38.存期格式化

function (trm) {var trmStr = '';console.log("trm==" + trm);var trms = trm.split('D');if (trms.length == 2 && trms[0].indexOf('M') != -1) {var mon = trms[0].substring(1, trms[0].length);console.log("mon==" + mon);var month = parseInt(mon);if (month < 12) {if (month != 0) {trmStr += month + "個月";}} else {if (month % 12 == 0) {trmStr += parseInt(month / 12) + "年";} else {trmStr += parseInt(month / 12) + "年" + parseInt(month % 12) + "個月";}}if (parseInt(trms[1]) > 0) {if (trmStr) {trmStr += "零";}trmStr += parseInt(trms[1]) + "天";}}return trmStr;};

39.計算總頁數,根據總條數和每頁顯示數(totalpage:總條數,pagesize:每頁顯示條數)

function (totalcount, pagesize) {var p = (parseInt(totalcount) + parseInt(pagesize) - 1) / parseInt(pagesize);return parseInt(p);};

?40.將‘YYYYMMDD’格式的字符串格式化成‘YYYY-MM-DD’的格式

function (dateStr) {var date = dateStr;if (date.length == 8) {date = date.substring(0, 4) + "-" + date.substring(4, 6) + "-" + date.substring(6, 8);}return date;};

41.理財,將幣種(數字)轉為漢字

function (ccycd) {var ccycdstr = "";switch (ccycd) {case "156":ccycdstr = "人民幣元";break;case "250":ccycdstr = "法國法郎";break;case "246":ccycdstr = "馬克";break;case "344":ccycdstr = "香港元";break;case "392":ccycdstr = "日元";break;case "826":ccycdstr = "英鎊";break;case "840":ccycdstr = "美元";break;case "978":ccycdstr = "歐元";break;default:// ccycdstr = "";break;}return ccycdstr;}

42.H5獲取自己本地IP地址

function grabLocalIps(onNewIP) { // onNewIp - your listener function for new IPsvar myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; //compatibility for firefox and chromevar pc = new myPeerConnection({iceServers: []}), // 空的ICE服務器(STUN或者TURN)noop = function () { },localIPs = {}, //記錄有沒有被調用到onNewIP這個listener上ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g;function ipIterate(ip) {if (!localIPs[ip]) onNewIP(ip);localIPs[ip] = true;}pc.createDataChannel(""); //create a bogus data channelvar handle = function (sdp) {sdp.sdp.split('\n').forEach(function (line) {if (line.indexOf('candidate') < 0) return;line.match(ipRegex).forEach(ipIterate);});pc.setLocalDescription(sdp, noop, noop);}// "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"if (navigator.userAgent.match(/^volcano.*/) ||navigator.userAgent.match(/Chrome\/\d*\./) && navigator.userAgent.match(/Chrome\/\d*\./)[0] <= 'Chrome/50.') {pc.createOffer(handle);} else {pc.createOffer().then(handle); // create offer and set local description}pc.onicecandidate = function (ice) { //listen for candidate eventsif (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;ice.candidate.candidate.match(ipRegex).forEach(ipIterate);};}

43.通過http請求獲取文本數據

function (url, sendData) {let promise = new Promise((resolve, reject) => {try {let response = "";let xmlhttp = new XMLHttpRequest();xmlhttp.onreadystatechange = function () {if (xmlhttp.status == 200 || xmlhttp.status == 0) {response = xmlhttp.responseText;if ('' !== response) {resolve({ status: xmlhttp.status, response });}} else if (xmlhttp.status == 400) {console.warn("Bad Request(parameter is not json format)");reject({ status: xmlhttp.status, response });} else if (xmlhttp.status == 500) {console.warn("Bad Request(parameter is not json array)");reject({ status: xmlhttp.status, response });} else {reject({ status: xmlhttp.status, response });}}xmlhttp.open("GET", url, true);xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");xmlhttp.send(sendData);} catch (e) {reject(e)}})return promise}

44.數組轉對象

function (list, key) {var object = {};if (!list) {return object;}for (var elemInx in list) {var elem = list[elemInx];if (!elem[key]) {return null;}object[elem[key]] = elem;}return object;}

45.精準乘法

function (arg1, arg2) {let m = 0,s1 = arg1.toString(),s2 = arg2.toString();try {m += s1.split(".")[1].length;} catch (e) {console.error("accMul.s1.split:", e);}try {m += s2.split(".")[1].length;} catch (e) {console.error("accMul.s2.split:", e);}return ((Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /Math.pow(10, m));}

46.判斷當前瀏覽器環境

function ($) {if ($ == "ie") {if (navigator.appName.indexOf("Microsoft") != -1)return true}else if ($ == "ns")if (navigator.appName.indexOf("Netscape") != -1)return true;return false};

47.?播放語音(src?語音文件url)

function (src) {let _ = window.document.getElementById("sound");try {if (this.env("ie")) {if (_ == null) {let bgSoundObj = window.document.createElement("bgsound")bgSoundObj.id = "sound";bgSoundObj.src = "";_ = bgSoundObj;}_.src = src;} else {if (_ == null) {let audioObj = window.document.createElement("audio")audioObj.id = "sound";audioObj.src = "";_ = audioObj;}_.src = src;_.play();}} catch (error) {console.error(error);}};try {apputils.speaker = new window.SpeechSynthesisUtterance();} catch (error) {apputils.speaker = {};}apputils.speakTimer = null;apputils.stopTimer = null;

48.檢測操作系統版本號(Mac?|?Unix?|?Android?|?Linux?|?Win2000?|?WinXP?|?Win2003?|?WinVistta?|?Win7?|?Win10?|?Volcano?|?other)

function detectOS() {var sUserAgent = navigator.userAgent;var isWin = (navigator.platform == "Win32") || (navigator.platform == "Windows");var isMac = (navigator.platform == "Mac68K") || (navigator.platform == "MacPPC") || (navigator.platform == "Macintosh") || (navigator.platform == "MacIntel");if (isMac) return "Mac";var isUnix = (navigator.platform == "X11") && !isWin && !isMac;if (isUnix) return "Unix";var isLinux = (String(navigator.platform).indexOf("Linux") > -1);var bIsAndroid = sUserAgent.toLowerCase().match(/android/i) == "android";if (isLinux) {if (bIsAndroid) return "Android";else return "Linux";}if (isWin) {var isWin2K = sUserAgent.indexOf("Windows NT 5.0") > -1 || sUserAgent.indexOf("Windows 2000") > -1;if (isWin2K) return "Win2000";var isWinXP = sUserAgent.indexOf("Windows NT 5.1") > -1 ||sUserAgent.indexOf("Windows XP") > -1;if (isWinXP) return "WinXP";var isWin2003 = sUserAgent.indexOf("Windows NT 5.2") > -1 || sUserAgent.indexOf("Windows 2003") > -1;if (isWin2003) return "Win2003";var isWinVista = sUserAgent.indexOf("Windows NT 6.0") > -1 || sUserAgent.indexOf("Windows Vista") > -1;if (isWinVista) return "WinVista";var isWin7 = sUserAgent.indexOf("Windows NT 6.1") > -1 || sUserAgent.indexOf("Windows 7") > -1;if (isWin7) return "Win7";var isWin10 = sUserAgent.indexOf("Windows NT 10.0") > -1 || sUserAgent.indexOf("Windows 10") > -1;if (isWin10) return "Win10";var isVolcano = sUserAgent.indexOf("volcano") > -1;if (isVolcano) return "Volcano";return "Windows";}return "other";};

49.判斷應用部署模式(CS?|?BS)

function getDeployMode() {let href = window.location.href;ContextUtils.localUtils.set("versionCheckPath", href)let str = href.substring(0, 4);if (str !== '') {if (str == 'http') {let httpadd = href.split('//')[1];if (httpadd.split(':') !== -1) {let ipAddress = httpadd.split(':')[0];if (ipAddress == 'localhost') {return 'CS'} else {if (ipAddress.split('.')[0] == '127') {return 'CS'} else {return 'BS'}}}return '';}if (str == 'file') return 'CS'return ''}return '';}

50.獲取JS字符串字節數,str?要計算的字符串(str的字節數,中文占2個字節,英文占1個字節)

function getStrByteLen(str) {let len = 0;if(str && typeof str == "string") {for(let i = 0; i < str.length; i++) {if(str.charCodeAt(i) > 255) {len += 2;} else {len += 1;}}}return len;}

51.格式化手機號(11位手機號)

function formatMobile(mobile) {let str = 0;if(mobile && typeof mobile == "string" && mobile.length == 11) {str = mobile.substring(0, 3) + " " + mobile.substring(3, 7) + " " + mobile.substring(7)}return str;}

52.左補兩位

function (str){if(str.length === 1){return "0" + str;}return str}

53.hex?->?dsp(hex?十六進制壓縮碼?如[0x12,?0x34,?0x56],?dsp?如?"123456")

function hex2Dsp(hex, lowerCase) {let dsp = []if(!hex || hex.length <= 0) {console.error(`傳入的hex為空或長度為0`);return "";}hex.forEach(item => {dsp.push(this.leftPad2Bit(item.toString(16)));})let dspStr = dsp.join("");if(lowerCase) {dspStr = dspStr.toLowerCase();} else {dspStr = dspStr.toUpperCase();}return dspStr;}

54.dsp?->?hex?

function (dsp) {let bytes;if(dsp && dsp.length % 2 === 0) {bytes = new Uint8Array(dsp.length / 2);for (let index = 0; index < dsp.length; index+=2) {let b = parseInt(dsp.substr(index, 2), 16);bytes[index/2] = b;}} else {console.error(`傳入的dsp非法,為空或者非偶數倍長度${dsp}`);}return bytes;}

55.分量亦或合成(itemA?分量A,itemB?分量B,bDsp?是否擴展?true,則傳入的itemA與itemB與返回的合成變量都為擴展碼,否則都為Uint8Array類型的壓縮碼數組)

function xor(itemA, itemB, bDsp) {let compA, compB;if(!itemA || !itemB) {console.error(`傳入的item為空`);return null;}if(bDsp) {compA = this.dsp2Hex(itemA);compB = this.dsp2Hex(itemB);} else {compA = itemA;compB = itemB;}if(compA.length != compB.length) {console.error(`compA:[${compA.length}]與compB: [${compB.length}]長度不一致!`);return null;}let len = compA.length;let result = new Uint8Array(len);for (let idx = 0; idx < len; idx++) {result[idx] = compA[idx] ^ compB[idx]}if(bDsp) {return this.hex2Dsp(result);} else {return result;}}return apputils; })();

好啦,本期常用的JavaScript工具類就分享到這里,如果你有更好的想法,歡迎留言!

記得關注這個文縐縐的前端程序員:孫叫獸的博客https://blog.csdn.net/weixin_41937552?spm=1010.2135.3001.5343

總結

以上是生活随笔為你收集整理的JavaScript常用工具类整理(总结版)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。