javascript-->常用封装方法

一、字符串操作

1.1、去除字符串空格

//去除空格  type 1-所有空格  2-前后空格  3-前空格 4-后空格
//ecDo.trim('  1235asd',1)
//result:1235asd
//这个方法有原生的方案代替,但是考虑到有时候开发PC站需要兼容IE8,所以就还是继续保留
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;
    }
}

  1.2字母大小写切换

 1 /*type
 2  1:首字母大写
 3  2:首页母小写
 4  3:大小写转换
 5  4:全部大写
 6  5:全部小写
 7  * */
 8 //ecDo.changeCase('asdasd',1)
 9 //result:Asdasd
10 changeCase: function (str, type) {
11     function ToggleCase(str) {
12         var itemText = ""
13         str.split("").forEach(
14             function (item) {
15                 if (/^([a-z]+)/.test(item)) {
16                     itemText += item.toUpperCase();
17                 } else if (/^([A-Z]+)/.test(item)) {
18                     itemText += item.toLowerCase();
19                 } else {
20                     itemText += item;
21                 }
22             });
23         return itemText;
24     }
25     switch (type) {
26         case 1:
27             return str.replace(/\b\w+\b/g, function (word) {
28                 return word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase();
29             });
30         case 2:
31             return str.replace(/\b\w+\b/g, function (word) {
32                 return word.substring(0, 1).toLowerCase() + word.substring(1).toUpperCase();
33             });
34         case 3:
35             return ToggleCase(str);
36         case 4:
37             return str.toUpperCase();
38         case 5:
39             return str.toLowerCase();
40         default:
41             return str;
42     }
43 }

1.3、字符串循环复制

 1 //repeatStr(str->字符串, count->次数)
 2 //ecDo.repeatStr('123',3)
 3 //"result:123123123"
 4 repeatStr: function (str, count) {
 5     var text = '';
 6     for (var i = 0; i < count; i++) {
 7         text += str;
 8     }
 9     return text;
10 }

1.4句中单词首字母大写 

 1 //这个我也一直在纠结,英文标题,即使是首字母大写,也未必每一个单词的首字母都是大写的,但是又不知道哪些应该大写,哪些不应该大写
 2 //ecDo.titleCaseUp('this is a title')
 3 //"This Is A Title"
 4 titleCaseUp: function (str, splitType) {
 5     var _splitType = splitType || /\s+/g;
 6     var strArr = str.split(_splitType),
 7         result = "", _this = this
 8     strArr.forEach(function (item) {
 9         result += _this.changeCase(item, 1) + ' ';
10     })
11     return this.trim(result, 4)
12 }  

1.5数组去重

1 removeRepeatArray: function (arr) {
2     return arr.filter(function (item, index, self) {
3         return self.indexOf(item) === index;
4     });
5 }

1.6数组的最大值,最小值

1 //数组最大值
2 maxArr: function (arr) {
3     return Math.max.apply(null, arr);
4 },
5 //数组最小值
6 minArr: function (arr) {
7     return Math.min.apply(null, arr);
8 }

1.7数组的求和、平均值

 1 //这一块的封装,主要是针对数字类型的数组
 2 //求和
 3 sumArr: function (arr) {
 4     return arr.reduce(function (pre, cur) {
 5         return pre + cur
 6     })
 7 }
 8 //数组平均值,小数点可能会有很多位,这里不做处理,处理了使用就不灵活!
 9 covArr: function (arr) {
10     return this.sumArr(arr) / arr.length;
11 },

1.8、从数组中随机获取元素

 1 //ecDo.randomOne([1,2,3,6,8,5,4,2,6])
 2 //2
 3 //ecDo.randomOne([1,2,3,6,8,5,4,2,6])
 4 //8
 5 //ecDo.randomOne([1,2,3,6,8,5,4,2,6])
 6 //8
 7 //ecDo.randomOne([1,2,3,6,8,5,4,2,6])
 8 //1
 9 randomOne: function (arr) {
10     return arr[Math.floor(Math.random() * arr.length)];
11 }

1.9、数组中重复的元素出现过几次

 1 //ecDo.getEleCount('asd56+asdasdwqe','a')
 2 //result:3
 3 //ecDo.getEleCount([1,2,3,4,5,66,77,22,55,22],22)
 4 //result:2
 5 getEleCount: function (obj, ele) {
 6     var num = 0;
 7     for (var i = 0, len = obj.length; i < len; i++) {
 8         if (ele === obj[i]) {
 9             num++;
10         }
11     }
12     return num;
13 }

1.10随即返回一个范围的数组

 1 //ecDo.randomNumber(5,10)
 2 //返回5-10的随机整数,包括5,10
 3 //ecDo.randomNumber(10)
 4 //返回0-10的随机整数,包括0,10
 5 //ecDo.randomNumber()
 6 //返回0-255的随机整数,包括0,255
 7 randomNumber: function (n1, n2) {
 8     if (arguments.length === 2) {
 9         return Math.round(n1 + Math.random() * (n2 - n1));
10     }
11     else if (arguments.length === 1) {
12         return Math.round(Math.random() * n1)
13     }
14     else {
15         return Math.round(Math.random() * 255)
16     }
17 }

1.11、Date日期

 1 //到某一个时间的倒计时
 2 //ecDo.getEndTime('2017/7/22 16:0:0')
 3 //result:"剩余时间6天 2小时 28 分钟20 秒"
 4 getEndTime: function (endTime) {
 5     var startDate = new Date(); //开始时间,当前时间
 6     var endDate = new Date(endTime); //结束时间,需传入时间参数
 7     var t = endDate.getTime() - startDate.getTime(); //时间差的毫秒数
 8     var d = 0,
 9         h = 0,
10         m = 0,
11         s = 0;
12     if (t >= 0) {
13         d = Math.floor(t / 1000 / 3600 / 24);
14         h = Math.floor(t / 1000 / 60 / 60 % 24);
15         m = Math.floor(t / 1000 / 60 % 60);
16         s = Math.floor(t / 1000 % 60);
17     }
18     return "剩余时间" + d + "天 " + h + "小时 " + m + " 分钟" + s + " 秒";
19 }

1.12、数据类型判断

 1 //ecDo.istype([],'array')
 2 //true
 3 //ecDo.istype([])
 4 //'[object Array]'
 5 istype: function (o, type) {
 6     if (type) {
 7         var _type = type.toLowerCase();
 8     }
 9     switch (_type) {
10         case 'string':
11             return Object.prototype.toString.call(o) === '[object String]';
12         case 'number':
13             return Object.prototype.toString.call(o) === '[object Number]';
14         case 'boolean':
15             return Object.prototype.toString.call(o) === '[object Boolean]';
16         case 'undefined':
17             return Object.prototype.toString.call(o) === '[object Undefined]';
18         case 'null':
19             return Object.prototype.toString.call(o) === '[object Null]';
20         case 'function':
21             return Object.prototype.toString.call(o) === '[object Function]';
22         case 'array':
23             return Object.prototype.toString.call(o) === '[object Array]';
24         case 'object':
25             return Object.prototype.toString.call(o) === '[object Object]';
26         case 'nan':
27             return isNaN(o);
28         case 'elements':
29             return Object.prototype.toString.call(o).indexOf('HTML') !== -1
30         default:
31             return Object.prototype.toString.call(o)
32     }
33 }

 1.13、获取特定class元素的节点

 1 //获取特定class元素的节点
 2 function elementsByClassName(nodes, classStr) {
 3     var oDivAll = nodes.getElementsByTagName('*');
 4     var res = [];
 5     for (var i = 0; i < oDivAll.length; i++) {
 6         if (oDivAll[i].className == classStr) {
 7             // console.log(oDivAll[i]);
 8             res.push(oDivAll[i]);
 9         }
10     }
11     return res;
12 };

1.14、封装$方法

 1 function $(str) {
 2 switch (str.charAt(0)) {
 3 case '#':
 4 return document.getElementById(str.slice(1));
 5 break;
 6 case '.':
 7 return elementsByClassName(document, str.slice(1));
 8 break;
 9 case '[':
10 return document.getElementsByName(str.slice(6, str.length - 1));
11 break;
12 default:
13 return document.getElementsByTagName(str);
14 }
15 };

 

 

posted @ 2020-10-27 21:47  诗亦0615  阅读(121)  评论(0)    收藏  举报