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

朱雀 2021-09-22 03:00 477阅读 0赞

导读:在前端开发过程中需要对常用的功能模块进行封装,常用的方法多次调用需要整合,保证组件的复用性与程序的可维护性,这里总结一下,便于后续的使用!

#

目录

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.两个浮点型相减,不丢失精度

  1. 两个浮点型相加,不丢失精度

35.按长度数组截取字符串,返回按长度分割成的字符串数组

36.按多长间隔截取字符串,n为长度,返回按长度分割成的字符串数组

37.格式化字符串

38.存期格式化

39.计算总页数,根据总条数和每页显示数(totalpage:总条数,pagesize:每页显示条数)

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

41.理财,将币种(数字)转为汉字

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

43.通过http请求获取文本数据

44.数组转对象

45.精准乘法

46.判断当前浏览器环境

  1. 播放语音(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类型的压缩码数组)


watermark_type_ZHJvaWRzYW5zZmFsbGJhY2s_shadow_50_text_Q1NETiBA5a2Z5Y-r5YW9_size_20_color_FFFFFF_t_70_g_se_x_16

1.全局声明工具类

  1. window.$App = window.$App || {};
  2. window.$App.AppUtils = (function () {
  3. let apputils = {};
  4. }

2.定时器

  1. /**
  2. * 定时器
  3. * @class Timer
  4. */
  5. apputils.Timer = ClassLoader.create();
  6. apputils.Timer.prototype = {
  7. initialize: function ($, A, _) {
  8. this._h = null;
  9. this.callback = $;
  10. this.interval = A;
  11. this.loop = _ ? true : false;
  12. this.running = false
  13. },
  14. onTimer: function () {
  15. if (!this.running) {
  16. try {
  17. this.running = true;
  18. this.callback();
  19. } finally {
  20. this.running = false;
  21. }
  22. }
  23. if (this.loop == false) {
  24. this.stop();
  25. }
  26. },
  27. stop: function () {
  28. clearInterval(this._h);
  29. },
  30. start: function () {
  31. this.stop();
  32. this._h = setInterval(this.onTimer.bind(this), this.interval * 1000);
  33. }
  34. };
  35. /**
  36. * 启动定时器
  37. * @param {*} times 倒计时时间,单位:秒
  38. * @param {*} callback 倒计时完成回调函数
  39. * @param {*} repeat 是否循环执行
  40. * @returns {object} 定时器对象,支持方法:start、stop
  41. * @function startTimer
  42. */
  43. apputils.startTimer = function (times, callback, repeat) {
  44. try {
  45. var timer = new this.Timer(function () {
  46. callback();
  47. }, times, repeat);
  48. timer.start();
  49. return timer;
  50. } catch (ajaxException) {
  51. alert(ajaxException.message);
  52. }
  53. return null;
  54. };

3.判断变量是否是一个值

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

4.判断变量是否为空

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

5.判断变量是否为一个数组

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

6.输入对象

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

7.将object对象转化为数组

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

8.对象转字符串

  1. function (o) {
  2. var str = "";
  3. if (this.isvalue(o)) {
  4. var t = Object.prototype.toString.apply(o);
  5. if (t === '[object Array]') {
  6. let a = [];
  7. for (var i = 0; i < o.length; i++) {
  8. /**
  9. * 此处原方法为a.push(this.tostring(o[i]));
  10. * 当o为字符串数组是,返回的结果出错,因此做了如下修改
  11. */
  12. if (this.tostring(o[i]).charAt(0) == '{') { //o为json数组时
  13. a.push(this.tostring(o[i]));
  14. } else { //o为字符串数组时
  15. a.push('"' + this.tostring(o[i]) + '"');
  16. }
  17. }
  18. str = '[' + a.join(',') + ']';
  19. a.length = 0;
  20. // a = null;
  21. } else if (t === '[object Date]') {
  22. var y = o.getFullYear();
  23. if (y < 1900) {
  24. y += 1900;
  25. }
  26. var m = o.getMonth() + 1;
  27. str = y + "-" + this.lpad(m, 2, '0') + "-" +
  28. this.lpad(o.getDate(), 2, '0') + " " +
  29. this.lpad(o.getHours(), 2, '0') + ":" +
  30. this.lpad(o.getMinutes(), 2, '0') + ":" +
  31. this.lpad(o.getSeconds(), 2, '0');
  32. } else if (t === '[object Object]') {
  33. let a = [],
  34. k;
  35. for (k in o) {
  36. var vt = Object.prototype.toString.apply(o[k]);
  37. if (vt === '[object Array]' || vt === '[object Object]') {
  38. a.push('"' + k + '":' + this.tostring(o[k]));
  39. } else {
  40. a.push('"' + k + '":"' + this.tostring(o[k]) + '"');
  41. }
  42. }
  43. str = '{' + a.join(',') + '}';
  44. a.length = 0;
  45. // a = null;
  46. } else {
  47. str = String(o);
  48. }
  49. }
  50. return str;
  51. };

9.json字符串转json对象

  1. function (str) {
  2. if (str == null || str == "") {
  3. return "";
  4. }
  5. if (str.charAt(0) != '(') {
  6. str = "(" + str + ")";
  7. }
  8. return eval(str);
  9. };

10.判断是否为数字

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

11.判断是否为整型

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

12.判断是否为浮点型

  1. function (str) {
  2. if (this.isint(str))
  3. return true;
  4. var re = /^[-]{0,1}(\d+)[.]+(\d+)$/;
  5. if (re.test(str)) {
  6. if (RegExp.$1 == 0 && RegExp.$2 == 0)
  7. return false;
  8. return true;
  9. } else {
  10. return false;
  11. }
  12. };

13.手机号验证

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

14.文本输入校验(中文、数字、字母、下划线、中文标点符号。 ; , : “ ”( ) 、 ? 《 》)

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

15.左填充(str 原字符串,len 目标长度,pad 填充的字符(默认:空格))

  1. function (str, len, pad) {
  2. str = this.tostring(str);
  3. if (typeof (len) === "undefined") {
  4. len = 0;
  5. }
  6. if (typeof (pad) === "undefined") {
  7. pad = ' ';
  8. }
  9. if (len + 1 >= str.length) {
  10. str = Array(len + 1 - str.length).join(pad) + str;
  11. }
  12. return str;
  13. };

16.右填充

  1. function (str, len, pad) {
  2. str = this.tostring(str);
  3. if (typeof (len) === "undefined") {
  4. len = 0;
  5. }
  6. if (typeof (pad) === "undefined") {
  7. pad = ' ';
  8. }
  9. if (len + 1 >= str.length) {
  10. str = str + Array(len + 1 - str.length).join(pad);
  11. }
  12. return str;
  13. };

17.消除空格

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

18.json对象转form数据

  1. function (json) {
  2. var str = "";
  3. for (var i in json) {
  4. str += "&" + i + "=" + json[i];
  5. }
  6. if (str.length > 1) {
  7. str = str.substring(1);
  8. }
  9. return str;
  10. };

19.IP有效验证

  1. function (ip) {
  2. var re = /(\d+)\.(\d+)\.(\d+)\.(\d+)/g; //匹配IP地址的正则表达式
  3. if (re.test(ip)) {
  4. var arr = ip.split(".");
  5. if (arr[0] > 254 || arr[1] > 254 || arr[2] > 254 || arr[3] > 254)
  6. return false;
  7. return true;
  8. } else {
  9. return false;
  10. }
  11. }

20.ASCII转HEX

  1. function (str) {
  2. if (!this.isvalue(str)) {
  3. return "";
  4. }
  5. var hex = "";
  6. for (var i = 0; i < str.length; ++i) {
  7. hex += str.charCodeAt(i).toString(16);
  8. }
  9. return hex;
  10. }

21.HEX转ASCII

  1. function (hex) {
  2. if (!this.isvalue(hex) || hex.length % 2 != 0) {
  3. return "";
  4. }
  5. var str = "";
  6. for (var i = 0; i < hex.length / 2; ++i) {
  7. var tmp = "0x" + hex[i * 2] + hex[i * 2 + 1];
  8. var charValue = String.fromCharCode(Number(tmp));
  9. str += charValue;
  10. }
  11. return str;
  12. }

22.金额自动加”,”分割(v_money 要格式化的金额,need_dot 是否需要精确到小数点后2位,{String} 格式化以后的金额,如:1,234,567.08)

  1. function (v_money, need_dot) {
  2. try {
  3. var p_number = parseFloat(v_money);
  4. if(isNaN(p_number)) {
  5. return v_money;
  6. }
  7. var p_string = "" + p_number;
  8. var p_idx = p_string.lastIndexOf(".");
  9. if (p_idx < 0) {
  10. p_idx = p_string.length;
  11. p_string = p_string + ".00";
  12. } else {
  13. var sarray = p_string.split('.');
  14. if (sarray[1] == '') {
  15. p_string = p_string + "00";
  16. } else if (sarray[1].length == 1) {
  17. p_string = p_string + "0";
  18. }
  19. }
  20. var p_ret = p_string.substring(p_idx);
  21. var p_temp = p_string.substring(0, p_idx);
  22. var p_length = p_temp.length;
  23. var p_count = Math.ceil(p_length / 3);
  24. for (var p_i = 0; p_i < p_count; p_i++) {
  25. var p_start_i = p_length - (p_i + 1) * 3;
  26. p_ret = p_temp.substring(p_start_i, p_start_i + 3) + p_ret;
  27. if (p_i < p_count - 1) {
  28. p_ret = "," + p_ret;
  29. }
  30. }
  31. if (need_dot == false) {
  32. var len = p_ret.indexOf(".");
  33. p_ret = p_ret.substring(0, len);
  34. }
  35. return p_ret;
  36. } catch (p_ee) {
  37. return "";
  38. }
  39. };

23.把金额数字转换为中文大写金额

  1. function (n) {
  2. var fraction = ['角', '分'];
  3. var digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
  4. var unit = [
  5. ['元', '万', '亿'],
  6. ['', '拾', '佰', '仟']
  7. ];
  8. var head = n < 0 ? '欠' : '';
  9. n = Math.abs(n);
  10. var s = '';
  11. for (let i = 0; i < fraction.length; i++) {
  12. s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
  13. }
  14. s = s || '整';
  15. n = Math.floor(n);
  16. for (let i = 0; i < unit[0].length && n > 0; i++) {
  17. var p = '';
  18. for (var j = 0; j < unit[1].length && n > 0; j++) {
  19. p = digit[n % 10] + unit[1][j] + p;
  20. n = Math.floor(n / 10);
  21. }
  22. s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
  23. }
  24. return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');
  25. };

24.生成验证码(len 验证码长度(默认:6),{String} 生成的验证码,)

  1. function (len) {
  2. var charactors = "1234567890";
  3. var value = '';
  4. if (!this.isint(len)) {
  5. len = 6;
  6. }
  7. for (let j = 1; j <= len; j++) {
  8. var i = parseInt(10 * Math.random());
  9. value = value + charactors.charAt(i);
  10. }
  11. return value;
  12. };

25.格式化账号显示(4位加空格)

  1. function (account) {
  2. if (!this.isvalue(account)) {
  3. return "";
  4. }
  5. if(account.startsWith("1")){
  6. if(account.length >= 17){
  7. account=account.substring(0,6)+"******"+account.substring(account.length-5);
  8. }
  9. }
  10. if(account.startsWith("6")){
  11. if(account.length >= 16){
  12. account=account.substring(0,4)+" **** **** "+account.substring(account.length-4);
  13. }
  14. }
  15. return account;
  16. };

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

  1. function (name) {
  2. if (!this.isvalue(name)) {
  3. return "";
  4. }
  5. var res = "";
  6. if (name.length == 1) {
  7. res += name;
  8. }
  9. if (name.length == 2) {
  10. res += "*";
  11. res += name.substring(name.length - 1);
  12. }
  13. if (name.length == 3) {
  14. res += name.substring(0, 1);
  15. res += "*";
  16. res += name.substring(2);
  17. }
  18. if (name.length > 3) {
  19. res += name.substring(0, 1);
  20. for(let i=0; i<name.length - 2; i++) {
  21. if(i <= 4) {
  22. res += "*";
  23. } else {
  24. break;
  25. }
  26. }
  27. res += name.substring(name.length - 1, name.length);
  28. }
  29. return res;
  30. };

27.字符串替换

  1. function (sourceString, startPos, encryptCount, encryptChar) {
  2. if (typeof sourceString != 'string')
  3. return sourceString;
  4. if (sourceString.length <= 0)
  5. return sourceString;
  6. if (typeof startPos != 'number')
  7. return sourceString;
  8. if (startPos <= 0)
  9. return sourceString;
  10. if (typeof encryptCount != 'number')
  11. return sourceString;
  12. if (encryptCount <= 0)
  13. return sourceString;
  14. if (startPos > sourceString.length)
  15. return sourceString;
  16. if ((startPos + encryptCount) > sourceString.length + 1)
  17. return sourceString;
  18. var str1 = sourceString.substr(0, startPos - 1);
  19. var str2 = sourceString.substr(startPos - 1, sourceString.length - startPos + 1);
  20. var str3 = '';
  21. var str4 = str2.substr(encryptCount, str2.length - encryptCount);
  22. for (var i = 0; i < encryptCount; i++) {
  23. str3 = str3 + encryptChar;
  24. }
  25. return str1 + str3 + str4;
  26. };

28.生成UUID(len UUID长度,默认标准36位,radix UUID基数,默认16)

  1. function (len, radix) {
  2. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  3. var uuid = [],
  4. i;
  5. radix = radix || chars.length;
  6. if (len) {
  7. // Compact form
  8. for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
  9. } else {
  10. // rfc4122, version 4 form
  11. var r;
  12. // rfc4122 requires these characters
  13. uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
  14. uuid[14] = '4';
  15. // Fill in random data. At i==19 set the high bits of clock sequence as
  16. // per rfc4122, sec. 4.1.5
  17. for (i = 0; i < 36; i++) {
  18. if (!uuid[i]) {
  19. r = 0 | Math.random() * 16;
  20. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
  21. }
  22. }
  23. }
  24. return uuid.join('');
  25. };

29.随机数生成36位UUID

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

30.解析json,结果返回

  1. function (str) {
  2. if (typeof str == 'string') {
  3. try {
  4. var obj = JSON.parse(str);
  5. if (typeof obj == 'object' && obj) {
  6. return obj;
  7. } else {
  8. return false;
  9. }
  10. } catch (e) {
  11. return false;
  12. }
  13. } else if (typeof str == 'object') {
  14. console.log('It is a object already!');
  15. return str;
  16. }
  17. console.log('It is not a string!')
  18. };

31.金额数据分转元

  1. function (money) {
  2. if (typeof money == 'string') {
  3. money = money.split(".").join("");//去调小数点
  4. var money2 = parseInt(money);
  5. money2 = money2.toString();
  6. if (money2.length > 2) {
  7. money2 = money2.substring(0, money2.length - 2) + "." + money2.substring(money2.length - 2, money2.length);
  8. } else if (money2 == 0) {
  9. money2 = "0.00";
  10. } else if (money2.length == 2) {
  11. money2 = "0." + money2;
  12. } else if (money2.length == 1) {
  13. money2 = "0.0" + money2;
  14. }
  15. return money2;
  16. }
  17. console.log('It is not a string!')
  18. };

32.金额数据元转分

  1. function (money) {
  2. if (typeof money == 'string') {
  3. var money2 = money.replaceAll(",", "");
  4. if (money2.indexOf(".") < 0) {
  5. money2 = money2 + "00"
  6. } else if (money2.length - money2.indexOf(".") == 2) {//一位小数
  7. money2 = money2.replace(".", "") + '0';
  8. } else {//两位小数
  9. money2 = money2.replace(".", "");
  10. }
  11. return money2;
  12. }
  13. console.log('It is not a string!')
  14. };

33.两个浮点型相减,不丢失精度

  1. function (arg1, arg2) {
  2. var r1, r2, m, n;
  3. try {
  4. r1 = arg1.toString().split(".")[1].length
  5. } catch (error) {
  6. r1 = 0
  7. }
  8. try {
  9. r2 = arg2.toString().split(".")[1].length
  10. } catch (error) {
  11. r2 = 0
  12. }
  13. m = Math.pow(10, Math.max(r1, r2));
  14. n = (r1 >= r2) ? r1 : r2;
  15. return ((arg1 * m - arg2 * m) / m).toFixed(n);
  16. };

34. 两个浮点型相加,不丢失精度

  1. function (arg1, arg2) {
  2. var r1, r2, m, n;
  3. try {
  4. r1 = arg1.toString().split(".")[1].length
  5. } catch (error) {
  6. r1 = 0
  7. }
  8. try {
  9. r2 = arg2.toString().split(".")[1].length
  10. } catch (error) {
  11. r2 = 0
  12. }
  13. m = Math.pow(10, Math.max(r1, r2));
  14. n = (r1 >= r2) ? r1 : r2;
  15. return ((arg1 * m + arg2 * m) / m).toFixed(n);
  16. };

35.按长度数组截取字符串,返回按长度分割成的字符串数组

  1. function (str, lens) {
  2. var arr = [];
  3. var len = lens.length;
  4. for (var i = 0; i < len; i++) {
  5. if (str.length >= lens[i]) {
  6. var strCut = str.substring(0, lens[i]);
  7. arr.push(strCut);
  8. str = str.substring(lens[i]);
  9. } else {
  10. // str = str;
  11. arr.push(str);
  12. }
  13. }
  14. return arr;
  15. };

36.按多长间隔截取字符串,n为长度,返回按长度分割成的字符串数组

  1. function (n) {
  2. var str = this;
  3. var arr = [];
  4. var len = Math.ceil(str.length / n);
  5. for (var i = 0; i < len; i++) {
  6. if (str.length >= n) {
  7. var strCut = str.substring(0, n);
  8. arr.push(strCut);
  9. str = str.substring(n);
  10. } else {
  11. // str = str;
  12. arr.push(str);
  13. }
  14. }
  15. return arr;
  16. };

37.格式化字符串

  1. function (fmtStr, obj) {
  2. if (!fmtStr.formatStr) {
  3. String.prototype.formatStr = function (argsObj) {
  4. var regexp = /\{(\d+)\}/g;
  5. var args = argsObj || [];
  6. var result = this.replace(regexp, function (m, i, o, n) {
  7. // console.log(o + n)
  8. return args[i];
  9. });
  10. return result.replace('%', "'");
  11. };
  12. }
  13. return fmtStr.formatStr(obj);
  14. };

38.存期格式化

  1. function (trm) {
  2. var trmStr = '';
  3. console.log("trm==" + trm);
  4. var trms = trm.split('D');
  5. if (trms.length == 2 && trms[0].indexOf('M') != -1) {
  6. var mon = trms[0].substring(1, trms[0].length);
  7. console.log("mon==" + mon);
  8. var month = parseInt(mon);
  9. if (month < 12) {
  10. if (month != 0) {
  11. trmStr += month + "个月";
  12. }
  13. } else {
  14. if (month % 12 == 0) {
  15. trmStr += parseInt(month / 12) + "年";
  16. } else {
  17. trmStr += parseInt(month / 12) + "年" + parseInt(month % 12) + "个月";
  18. }
  19. }
  20. if (parseInt(trms[1]) > 0) {
  21. if (trmStr) {
  22. trmStr += "零";
  23. }
  24. trmStr += parseInt(trms[1]) + "天";
  25. }
  26. }
  27. return trmStr;
  28. };

39.计算总页数,根据总条数和每页显示数(totalpage:总条数,pagesize:每页显示条数)

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

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

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

41.理财,将币种(数字)转为汉字

  1. function (ccycd) {
  2. var ccycdstr = "";
  3. switch (ccycd) {
  4. case "156":
  5. ccycdstr = "人民币元";
  6. break;
  7. case "250":
  8. ccycdstr = "法国法郎";
  9. break;
  10. case "246":
  11. ccycdstr = "马克";
  12. break;
  13. case "344":
  14. ccycdstr = "香港元";
  15. break;
  16. case "392":
  17. ccycdstr = "日元";
  18. break;
  19. case "826":
  20. ccycdstr = "英镑";
  21. break;
  22. case "840":
  23. ccycdstr = "美元";
  24. break;
  25. case "978":
  26. ccycdstr = "欧元";
  27. break;
  28. default:
  29. // ccycdstr = "";
  30. break;
  31. }
  32. return ccycdstr;
  33. }

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

  1. function grabLocalIps(onNewIP) { // onNewIp - your listener function for new IPs
  2. var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; //compatibility for firefox and chrome
  3. var pc = new myPeerConnection({
  4. iceServers: []
  5. }), // 空的ICE服务器(STUN或者TURN)
  6. noop = function () { },
  7. localIPs = {}, //记录有没有被调用到onNewIP这个listener上
  8. ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g;
  9. function ipIterate(ip) {
  10. if (!localIPs[ip]) onNewIP(ip);
  11. localIPs[ip] = true;
  12. }
  13. pc.createDataChannel(""); //create a bogus data channel
  14. var handle = function (sdp) {
  15. sdp.sdp.split('\n').forEach(function (line) {
  16. if (line.indexOf('candidate') < 0) return;
  17. line.match(ipRegex).forEach(ipIterate);
  18. });
  19. pc.setLocalDescription(sdp, noop, noop);
  20. }
  21. // "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"
  22. if (navigator.userAgent.match(/^volcano.*/) ||
  23. navigator.userAgent.match(/Chrome\/\d*\./) && navigator.userAgent.match(/Chrome\/\d*\./)[0] <= 'Chrome/50.') {
  24. pc.createOffer(handle);
  25. } else {
  26. pc.createOffer().then(handle); // create offer and set local description
  27. }
  28. pc.onicecandidate = function (ice) { //listen for candidate events
  29. if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
  30. ice.candidate.candidate.match(ipRegex).forEach(ipIterate);
  31. };
  32. }

43.通过http请求获取文本数据

  1. function (url, sendData) {
  2. let promise = new Promise((resolve, reject) => {
  3. try {
  4. let response = "";
  5. let xmlhttp = new XMLHttpRequest();
  6. xmlhttp.onreadystatechange = function () {
  7. if (xmlhttp.status == 200 || xmlhttp.status == 0) {
  8. response = xmlhttp.responseText;
  9. if ('' !== response) {
  10. resolve({ status: xmlhttp.status, response });
  11. }
  12. } else if (xmlhttp.status == 400) {
  13. console.warn("Bad Request(parameter is not json format)");
  14. reject({ status: xmlhttp.status, response });
  15. } else if (xmlhttp.status == 500) {
  16. console.warn("Bad Request(parameter is not json array)");
  17. reject({ status: xmlhttp.status, response });
  18. } else {
  19. reject({ status: xmlhttp.status, response });
  20. }
  21. }
  22. xmlhttp.open("GET", url, true);
  23. xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  24. xmlhttp.send(sendData);
  25. } catch (e) {
  26. reject(e)
  27. }
  28. })
  29. return promise
  30. }

44.数组转对象

  1. function (list, key) {
  2. var object = {};
  3. if (!list) {
  4. return object;
  5. }
  6. for (var elemInx in list) {
  7. var elem = list[elemInx];
  8. if (!elem[key]) {
  9. return null;
  10. }
  11. object[elem[key]] = elem;
  12. }
  13. return object;
  14. }

45.精准乘法

  1. function (arg1, arg2) {
  2. let m = 0,
  3. s1 = arg1.toString(),
  4. s2 = arg2.toString();
  5. try {
  6. m += s1.split(".")[1].length;
  7. } catch (e) {
  8. console.error("accMul.s1.split:", e);
  9. }
  10. try {
  11. m += s2.split(".")[1].length;
  12. } catch (e) {
  13. console.error("accMul.s2.split:", e);
  14. }
  15. return (
  16. (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
  17. Math.pow(10, m)
  18. );
  19. }

46.判断当前浏览器环境

  1. function ($) {
  2. if ($ == "ie") {
  3. if (navigator.appName.indexOf("Microsoft") != -1)
  4. return true
  5. }
  6. else if ($ == "ns")
  7. if (navigator.appName.indexOf("Netscape") != -1)
  8. return true;
  9. return false
  10. };

47. 播放语音(src 语音文件url)

  1. function (src) {
  2. let _ = window.document.getElementById("sound");
  3. try {
  4. if (this.env("ie")) {
  5. if (_ == null) {
  6. let bgSoundObj = window.document.createElement("bgsound")
  7. bgSoundObj.id = "sound";
  8. bgSoundObj.src = "";
  9. _ = bgSoundObj;
  10. }
  11. _.src = src;
  12. } else {
  13. if (_ == null) {
  14. let audioObj = window.document.createElement("audio")
  15. audioObj.id = "sound";
  16. audioObj.src = "";
  17. _ = audioObj;
  18. }
  19. _.src = src;
  20. _.play();
  21. }
  22. } catch (error) {
  23. console.error(error);
  24. }
  25. };
  26. try {
  27. apputils.speaker = new window.SpeechSynthesisUtterance();
  28. } catch (error) {
  29. apputils.speaker = {};
  30. }
  31. apputils.speakTimer = null;
  32. apputils.stopTimer = null;

48.检测操作系统版本号(Mac | Unix | Android | Linux | Win2000 | WinXP | Win2003 | WinVistta | Win7 | Win10 | Volcano | other)

  1. function detectOS() {
  2. var sUserAgent = navigator.userAgent;
  3. var isWin = (navigator.platform == "Win32") || (navigator.platform == "Windows");
  4. var isMac = (navigator.platform == "Mac68K") || (navigator.platform == "MacPPC") || (navigator.platform == "Macintosh") || (navigator.platform == "MacIntel");
  5. if (isMac) return "Mac";
  6. var isUnix = (navigator.platform == "X11") && !isWin && !isMac;
  7. if (isUnix) return "Unix";
  8. var isLinux = (String(navigator.platform).indexOf("Linux") > -1);
  9. var bIsAndroid = sUserAgent.toLowerCase().match(/android/i) == "android";
  10. if (isLinux) {
  11. if (bIsAndroid) return "Android";
  12. else return "Linux";
  13. }
  14. if (isWin) {
  15. var isWin2K = sUserAgent.indexOf("Windows NT 5.0") > -1 || sUserAgent.indexOf("Windows 2000") > -1;
  16. if (isWin2K) return "Win2000";
  17. var isWinXP = sUserAgent.indexOf("Windows NT 5.1") > -1 ||
  18. sUserAgent.indexOf("Windows XP") > -1;
  19. if (isWinXP) return "WinXP";
  20. var isWin2003 = sUserAgent.indexOf("Windows NT 5.2") > -1 || sUserAgent.indexOf("Windows 2003") > -1;
  21. if (isWin2003) return "Win2003";
  22. var isWinVista = sUserAgent.indexOf("Windows NT 6.0") > -1 || sUserAgent.indexOf("Windows Vista") > -1;
  23. if (isWinVista) return "WinVista";
  24. var isWin7 = sUserAgent.indexOf("Windows NT 6.1") > -1 || sUserAgent.indexOf("Windows 7") > -1;
  25. if (isWin7) return "Win7";
  26. var isWin10 = sUserAgent.indexOf("Windows NT 10.0") > -1 || sUserAgent.indexOf("Windows 10") > -1;
  27. if (isWin10) return "Win10";
  28. var isVolcano = sUserAgent.indexOf("volcano") > -1;
  29. if (isVolcano) return "Volcano";
  30. return "Windows";
  31. }
  32. return "other";
  33. };

49.判断应用部署模式(CS | BS)

  1. function getDeployMode() {
  2. let href = window.location.href;
  3. ContextUtils.localUtils.set("versionCheckPath", href)
  4. let str = href.substring(0, 4);
  5. if (str !== '') {
  6. if (str == 'http') {
  7. let httpadd = href.split('//')[1];
  8. if (httpadd.split(':') !== -1) {
  9. let ipAddress = httpadd.split(':')[0];
  10. if (ipAddress == 'localhost') {
  11. return 'CS'
  12. } else {
  13. if (ipAddress.split('.')[0] == '127') {
  14. return 'CS'
  15. } else {
  16. return 'BS'
  17. }
  18. }
  19. }
  20. return '';
  21. }
  22. if (str == 'file') return 'CS'
  23. return ''
  24. }
  25. return '';
  26. }

50.获取JS字符串字节数,str 要计算的字符串(str的字节数,中文占2个字节,英文占1个字节)

  1. function getStrByteLen(str) {
  2. let len = 0;
  3. if(str && typeof str == "string") {
  4. for(let i = 0; i < str.length; i++) {
  5. if(str.charCodeAt(i) > 255) {
  6. len += 2;
  7. } else {
  8. len += 1;
  9. }
  10. }
  11. }
  12. return len;
  13. }

51.格式化手机号(11位手机号)

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

52.左补两位

  1. function (str){
  2. if(str.length === 1){
  3. return "0" + str;
  4. }
  5. return str
  6. }

53.hex -> dsp(hex 十六进制压缩码 如[0x12, 0x34, 0x56], dsp 如 “123456”)

  1. function hex2Dsp(hex, lowerCase) {
  2. let dsp = []
  3. if(!hex || hex.length <= 0) {
  4. console.error(`传入的hex为空或长度为0`);
  5. return "";
  6. }
  7. hex.forEach(item => {
  8. dsp.push(this.leftPad2Bit(item.toString(16)));
  9. })
  10. let dspStr = dsp.join("");
  11. if(lowerCase) {
  12. dspStr = dspStr.toLowerCase();
  13. } else {
  14. dspStr = dspStr.toUpperCase();
  15. }
  16. return dspStr;
  17. }

54.dsp -> hex

  1. function (dsp) {
  2. let bytes;
  3. if(dsp && dsp.length % 2 === 0) {
  4. bytes = new Uint8Array(dsp.length / 2);
  5. for (let index = 0; index < dsp.length; index+=2) {
  6. let b = parseInt(dsp.substr(index, 2), 16);
  7. bytes[index/2] = b;
  8. }
  9. } else {
  10. console.error(`传入的dsp非法,为空或者非偶数倍长度${dsp}`);
  11. }
  12. return bytes;
  13. }

55.分量亦或合成(itemA 分量A,itemB 分量B,bDsp 是否扩展 true,则传入的itemA与itemB与返回的合成变量都为扩展码,否则都为Uint8Array类型的压缩码数组)

  1. function xor(itemA, itemB, bDsp) {
  2. let compA, compB;
  3. if(!itemA || !itemB) {
  4. console.error(`传入的item为空`);
  5. return null;
  6. }
  7. if(bDsp) {
  8. compA = this.dsp2Hex(itemA);
  9. compB = this.dsp2Hex(itemB);
  10. } else {
  11. compA = itemA;
  12. compB = itemB;
  13. }
  14. if(compA.length != compB.length) {
  15. console.error(`compA:[${compA.length}]与compB: [${compB.length}]长度不一致!`);
  16. return null;
  17. }
  18. let len = compA.length;
  19. let result = new Uint8Array(len);
  20. for (let idx = 0; idx < len; idx++) {
  21. result[idx] = compA[idx] ^ compB[idx]
  22. }
  23. if(bDsp) {
  24. return this.hex2Dsp(result);
  25. } else {
  26. return result;
  27. }
  28. }
  29. return apputils;
  30. })();

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

记得关注这个文绉绉的前端程序员:孙叫兽的博客icon-default.png?t=L892https://blog.csdn.net/weixin\_41937552?spm=1010.2135.3001.5343

发表评论

表情:
评论列表 (有 0 条评论,477人围观)

还没有评论,来说两句吧...

相关阅读