自己封装函数时,参数最好不要超过3个,若要超过,可以用数组或者对象;
1. 利用(Math.random
)写指定范围的随机数
2. 补零
3. 数组去重
4. 排序
5. 敏感词过滤
6. 判断数组中是否存在某一条数据,结果返回布尔值
7. 商品列表
8. 格式化日期
9. 获取行内样式
1. 利用(Math.random
)写指定范围的随机数;
(1)随机数的公共方法
//Math.random()//0~1之间的随机数
//Math.round(Math.random()) 随机数四舍五入取整;
function random(a,b){return Math.round(Math.random()*(b-a) + a);
}
(2)数字字母的数据验证码
var str = "";//用来生成一个随机验证码库for(var i=0; i<4; i++){var num = random(48,57);var sStr = random(97,122);var lStr = random(65,90);str = str + String.fromCharCode(num) + String.fromCharCode(sStr) + String.fromCharCode(lStr)}var result = "";for(var i=0; i<4; i++){var index = random(0,str.length-1);result += str[index];}console.log(result);function random(a,b){return Math.round(Math.random()*(b-a)+a);}
(3)十六进制的随机色
var r = random(0,255).toString(16);var g = random(0,255).toString(16);var b = random(0,255).toString(16);var str = "#"+createZero(r)+createZero(g)+createZero(b);document.body.style.backgroundColor = str;function createZero(n){if(n < 10 || n.length < 2){return "0" + n;} else {return "" + n;}}function random(a,b){return Math.round(Math.random()*(b-a)+a);}
2. 补零
function crateZero(n){if(n < 10 || n.length < 2){//数值和字符的补零return "0" + n;} else {return "" + n;}
}
3. 数组去重
(1)利用 对象 添加属性得到undefined;
优点: 可以计算出重复的个数;
缺点: 当数字和字符形式的数字相同时,且同时出现在同一个数组中,该方法不好用;
var arr = ['a','b','a','a','b','a'];
var obj = {};
for(var i=0; i<arr.length; i++){if( obj[arr[i]] ){obj[arr[i]]++;} else {obj[arr[i]] = 1}
}
console.log(obj);//{a:4, b:2}
var newArr = [];
for(var key in obj){newArr.push(key);
}
console.log(newArr);//[a,b]
(2)用 indexOf()
方法
var arr = [3,5,6,2,1,8,5,4,2,"2"];var newArr = [];
for(var i = 0;i<arr.length; i++){if(newArr.indexOf(arr[i]) == -1){newArr.push(arr[i]);}
}
console.log(newArr);//(8) [3, 5, 6, 2, 1, 8, 4, "2"]
(3)利用 ES6 的 Set() 方法去重(不严格)
function norepeat(arr){var s = new Set(arr);var newArr = [];for(var i of s){newArr.push(i);}return newArr;
}
4. 排序
(1)冒泡排序
var arr = [12,9,6,8,3,4];
for(j = 0; j<arr.length-1; j++){for(var i = 0; i<arr.length-1-j; i++){if(arr[i] > arr[i+1]){var temp = arr[i];arr[i] = arr[i+1];arr[i+1] = temp; }}
}
(2)比较排序
var arr = [3,1,2,4,6,9];console.log(arr);for(var i = 0;i<arr.length; i++){var min = arr[i];//假设为最小值var minIndex = i;//最小值的indexfor(var j = i+1; j<arr.length; j++){ //i与后面所有的值做比较if(min > arr[j]){min = arr[j];minIndex = j;}}arr[minIndex] = arr[i];arr[i] = min}console.log(arr);
(3)用 sort()
方法排序(解决 sort()
按位排序问题)
//升序:
var arr2 = [2,101,6,58,3]
arr2.sort(function(a,b){return a-b;})
console.log(arr2);//(5) [2, 3, 6, 58, 101]//降序:
arr2.sort(function(a,b){return b-a;})
console.log(arr2);//(5) [101, 58, 6, 3, 2]
5. 敏感词过滤
(1)利用字符的 replace()
方法(这种方法耗内存,最好用正则)
var msg = ['fuck','tm','nnd','sb','sx'];//敏感词库
var str = "fuck,你tm真让人无语";//要说的话
for(var i=0;i<str.length;i++){msg.forEach( function (val,index){str = str.replace(val,"**");})
}
console.log(str);//**,你**真让人无语
(2)正则
var msg = ['fuck','tm','nnd','sb','sx'];//敏感词库
var str = "fuck,你tm真让人无语";//要说的话
for(var i=0; i<msg.length; i++){var reg = new RegExp(msg[i],"g");str = str.replace(reg,"**")
}
console.log(str);//**,你**真让人无语
6. 判断数组中是否存在某一条数据,结果返回布尔值;
var arr = [2,4,6,5,8,1]
function has(arr,num){for(var i=0; i<arr.length; i++){if(arr[i] === num){return true;}}return false;
}
console.log(has(arr,"1"));//false
console.log(has(arr,1));//true
7. 商品列表
(1)字符串拼接的方法
var str = "";for(var i=0; i<data.length; i++){str += '<li>'+'<img src="'+data[i].src+'" alt="暂无图片">'+'<p>'+data[i].title+'</p>'+'<span>¥ '+data[i].price+'</span>'+'</li>'}var ul = document.querySelector('ul');ul.innerHTML = str;
8. 格式化日期
console.log(new Date()); //Tue Oct 08 2019 14:26:59 GMT+0800 (中国标准时间)
(1)将标准格式的时间改为: yyyy-mm-dd hh:mm:ss
var date = createDate("-");
console.log(date); //Tue Oct 08 2019 14:26:59 GMT+0800 (中国标准时间)
function createDate(sign){var d = new Date();var y = d.getFullYear();var m = d.getMonth()+1;var mydate = d.getDate();var day = d.getDay();var h = d.getHours();var min = d.getMinutes();var s = d.getSeconds();switch(day){case 0: day = "星期日";bread;case 1: day = "星期一";bread;case 2: day = "星期二";bread;case 3: day = "星期三";bread;case 4: day = "星期四";bread;case 5: day = "星期五";bread;case 6: day = "星期六";bread;};return y +sign+ createZone(m) +sign+ createZone(mydate) +" "+ day +" "+ createZone(h) +":"+ createZone(min) +":"+ createZone(s);
}function createZone(n){if(n<10 || n.length<2){return "0"+n;} else {return ""+n;}
}
(2)时间戳 转 日期格式
时间戳为10位需*1000,时间戳为13位的话不需乘1000
console.log(new Date(1570518752234)); //Tue Oct 08 2019 14:26:59 GMT+0800 (中国标准时间)
9. 获取行内样式
function getStyle(ele,""){if(ele.currentStyle){//return ele.currentStyle.width;//当对象身上的属性是变量时,要用 [] 来访问,而不用 .return ele.currentStyle[attr];} else {return getComputedStyle(ele,false)[attr];
}
console.log( getStyle(obox,"height") )
10. 事件
(1)事件冒泡
var e = eve || window.event;
function stopBubble(e){if(e.stopPropagation){e.stopPropagation();} else {e.cancelBubble = true;}
}
(2)阻止默认事件
function stopDefault(e){if(e.preventDefault){e.preventDefault();} else {e.returnValue = false;}
}
(3)事件监听
- 添加监听:
function addEvent(ele,type,callback){if(ele.addEventListener){ele.addEventListener(type,callback,false);} else if(ele.attachEvent){ele.attachEvent("on"+type,callback);} else {ele["on"+type] = callback;}
}addEvent(obox,"click",function(){console.log(1);
})//或者
addEvent(obox,"click",function())
- 删除事件监听:
function removeEvent(ele,type,callback){if(ele.removeEventListener){ele.removeEventListener(type,callback,false);} else if(ele.detachEvent){ele.detachEvent("on"+type,callback):} else {ele["on"+type] = null;}
}removeEvent(obox,click,fn);
11. 封装 cookie
(1)添加:
function setCookie(key,value,num){
//不传num,默认会话级别。if(num){var d = new Date();d.setDate(d.getDate()+num);document.cookie = key+"="+value+";expires="+d;} else {document.cookie = key+"="+value; }
}
(2)删除:
function removeCookie(key){setCookie(key,"suiyizhi",-1);
}
(3)获取:
function getCookie(key){var str = document.cookie;for(var i=0; i<str.split("; ").length; i++){if(str.split("; ")[i].split("=")[0] == key){return str.split("; ")[i].split("=")[1];}}return ""; //没有该cookie时返回"",若不写这一句,则会显示成undfined。
}
12. 判断一个字符串是否以数字开头?
var str1 = "1a3";
var str2 = "aaa";
console.log( isNaN(parseInt(str1)) ); //false 是数字开头
console.log( isNaN(parseInt(str2)) ); //true 不是数字开头
13. 过滤空白节点
var list = obox.childNodes;
for(var i=0; i<list.length; i++){ //遍历所有节点if(list[i].nodeType == 1){ //元素节点的nodeType=1console.log(list[i]);}
}