简介:本文收集了我常用的JavaScript代码片段,欢迎提意见!

大灰狼边敲门边说:“小兔子乖乖,把门儿开开!”
小兔子听到后,连忙去开门:“来喽!”
兔妈妈对小兔子喊道:“不许开!是大灰狼!”
大灰狼在门口感叹道:“哎,骗一个女孩容易,骗一个女人难呀!”

JavaScript动态加载

//NO.1
functionloadScript(url, callback){var script = document.createElement ("script")script.type= "text/javascript";if (script.readyState){ //IEscript.onreadystatechange = function(){if (this.readyState == "loaded" || this.readyState == "complete"){this.onreadystatechange = null;callback();}};}else { //Othersscript.onload = function(){callback();};}script.src=url;document.getElementsByTagName("head")[0].appendChild(script);
}//NO.2
functionloadScript(url, callback){var xhr = newXMLHttpRequest();xhr.open("get", url, true);xhr.onreadystatechange= function(){if (xhr.readyState == 4){if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){var script = document.createElement ("script");script.type= "text/javascript";script.text=xhr.responseText;document.body.appendChild(script);callback();}}};xhr.send(null);
}

View Code

DOM加载完执行

functiondomLoad(fn){if(document.addEventListener){document.addEventListener("DOMContentLoaded", fn, false);}else{if(window.ActiveXObject){document.write("<script id='ie_onload' defer src='javascript:void(0)'><\/script>");document.getElementById("ie_onload").onreadystatechange = function(){if(this.readyState == "complete"){this.onreadystatechange = null;fn();}}}if(/WebKit/i.test(navigator.userAgent)){var _timer = setInterval(function(){if(/loaded|complete/.test(document.readyState)){clearInterval(_timer);fn();}},10);}}
}

View Code

是否标准模式(IE)

function isCompatMode(){return document.compatMode == 'CSS1Compat';}

View Code

Link规则操作

//添加第一条规则//insertRule(sheet, 'body', 'background-color:red', 0);
functioninsertRule(sheet, selectorText, cssText, position) {if(sheet.insertRule) {sheet.insertRule(selectorText+ ' { ' + cssText + ' }', position);}else if(sheet.addRule) {sheet.addRule(selectorText, cssText, position);}
}//删除第一条规则//deleteRule(sheet, 0);
functiondeleteRule(sheet, position) {if(sheet.deleteRule) {sheet.deleteRule(position);}else if(sheet.removeRule) {sheet.removeRule(position);}
}

View Code

加载样式表

functionaddSheet(url){var oLink = document.createElement('link'),oHead = document.getElementsByTagName('head')[0];oLink.rel= 'stylesheet';oLink.type= 'text/css';oLink.href=url;oHead.appendChild(oLink);
}

View Code

获取CSS样式

functiongetStyle(o, attr){if(o.currentStyle){returno.currentStyle[attr];}else{return getComputedStyle(o,false)[attr];}
}

View Code

getByClass

functiongetElementsByClassName(classname, parent, nodename) {var parent = parent || document, nodename = nodename || "*";if(parent.getElementsByClassName){returnparent.getElementsByClassName(classname);}else{var l =parent.getElementsByTagName(nodename);return function() {var res =[];for (var i = 0, j = l.length; i < j; i++) {if(l[i].className){var name = " " + l[i].className + " ";if (name.indexOf(" " + classname + " ") != -1) {res.push(l[i]);}}}returnres;} ();}
}

View Code

hasClass

functionhasClass (element, className){return element.className.match(new RegExp('(\\s|^)'+ className +'(\\s|$)'));
}

View Code

addClass

functionaddClass(element, cName) {if (!hasClass(element, cName)) {element.className+= ' ' +cName;}
}

View Code

removeClass

functionremoveClass(element, cName) {if(hasClass(element, cName)) {element.className= element.className.replace(new RegExp('(\\s|^)' + cName + '(\\s|$)'), ' ');}
}

View Code

JSONP调用

<script src="http://www.xxx.com?name=fnCall"></script>
<script>
functionfnCall(info){//在前台提供一个方法fnCall的方法//http://www.xxx.com?name=fnCall 在(后台/其他页面)自动获取fnCall的名字并且执行
}</script>

View Code

获取服务器时间

functiongetNowDate(callback){var xhr = newXMLHttpRequest();xhr.open('get', 'null.txt', true); //null.txt不存在,我们不需要xhr.onreadystatechange = function(){if(xhr.readyState == 3){ //状态3响应callback(xhr.getResponseHeader('Date')); //返回时间,那么可以利用获得的时间做倒计时程序了。
}};xhr.send(null);
}

View Code

Cookie操作

functionCookie(name, value, options){if(typeof value != 'undefined'){options= options ||{};if(value === null){options.expires= -1; //过期
}var expires = '';//存在时间选项if(options.expires && (typeof options.expires == 'number' ||options.expires.toUTCString)){vardate;if(typeof options.expires == 'number'){date= newDate();date.setTime(date.getTime()+ (options.expires * 24 * 60 * 60 * 1000));}else{date=options.expires;}expires= '; expires='+date.toUTCString();}var path = options.path ? '; path='+options.path : '';var domain = options.domain ? '; domain='+options.domain : '';var secure = options.secure ? '; secure' : '';//写入cookiedocument.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');}else{//读取cookievar cookValue = null;if(document.cookie && document.cookie != ''){var cookie = document.cookie.split(';');for(var i = 0, len = cookie.length; i < len; i++){var c = cookie[i].replace(/^\s+|\s+$/g, '');if(c.substring(0, name.length + 1) == (name + '=')){cookValue= decodeURIComponent(c.substring(name.length + 1));break;}}}returncookValue;}
}//设置
Cookie("user", "Jununx");//获取
Cookie("user");//删除
Cookie("user", null);

View Code

base64编码解码

functionb64Encode(str) {returnbtoa(unescape(encodeURIComponent(str)));
}functionb64Decode(str) {returndecodeURIComponent(escape(atob(str)));
}

View Code

浏览器判断

var browser = function() {var u =navigator.userAgent.toLowerCase();return{ version: (u.match(/.+(?:rv|it|ra|ie|chrome|micromessenger|version)[\/: ]([\d.]+)/) || [])[1],     safari:/safari/.test(u) && !/chrome/.test(u), opera:/opera/.test(u), msie:/msie|like gecko$/.test(u) && !/opera/.test(u), firefox:/firefox/.test(u) && !/(compatible|webkit)/.test(u),chrome:/chrome/.test(u) && /safari/.test(u),  mobile:!!/applewebkit.*mobile.*/.test(u),ios:!!/\(i[^;]+;( u;)? cpu.+mac os x/.test(u),android:/android|linux/.test(u), //android或uciPhone: /iphone/.test(u),iPad:/ipad/.test(u),weChat:/micromessenger/.test(u) //微信
};
};

View Code

IE版本判断

var _IE = (function(){var v = 3, div = document.createElement('div'), all = div.getElementsByTagName('i');while(div.innerHTML= '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',all[0]);return v > 4 ? v : false;
}());

View Code

阶乘缓存

functionmemfactorial(n){if(!memfactorial.cache){memfactorial.cache={"0" : 1,"1" : 1};}if(!memfactorial.cache.hasOwnProperty(n)){memfactorial.cache[n]= n * memfactorial(n - 1);}returnmemfactorial.cache[n];
}

View Code

获取字符串长度

//NO.1
String.prototype.sLen = function(){var b = 0, l = this.length;if(l){for(var i = 0; i < l; i++){if(this.charCodeAt(i) > 255){b+= 2;}else{b++;}}returnb;}else{return 0;}
};//NO.2
String.prototype.sLen = function(){var b = 0, l = this.length;if(l){for(var i = 0; i < l; i++){var c = this.charAt(i);if(escape(c).length > 4){b+= 2;}else if(c != '\r'){b++;}}returnb;}else{return 0;}
};//NO.3
String.prototype.sLen = function(){var b = 0, l = this.length;if(l){for(var i = 0; i < l; i++){var c = this.charAt(i);if(/^[\u0000-\u00ff]$]/.test(c)){b++;}else if(c != '\r'){b+= 2;}}returnb;}else{return 0;}
};//NO.4
String.prototype.sLen = function(){var s = this.replace(/[^\x00-\xff]/g, "**");returns.length;
};

View Code

判断数据类型

var isType = function(obj, type){return Object.prototype.toString.call(obj) === '[object '+ type +']';
};

View Code

获取窗口位置

functionsereen(){return{left : window.screenLeft||window.scrollX,top : window.screenTop||window.scrollY};
}

View Code

获取可视窗口大小

functionclient(){//IE6不加dtd会进入怪癖模式,client需要通过document.body获取return{width : document.documentElement.clientWidth||document.body.clientWidth,height : document.documentElement.clientHeight||document.body.clientHeight};
}

View Code

获取scrollTop

functiongetScrollTop(){if(typeof pageYOffset!= 'undefined'){returnpageYOffset;}else{return (document.body ||document.documentElement).scrollTop;}
}

View Code

滚动到指定区域

el.scrollIntoView()

View Code

今天星期几

"今天是星期" + "天一二三四五六".charAt(new Date().getDay())

View Code

页面是否在iframe里

if(self==top){//not in iframe
}else{//in iframe
}

View Code

返回最小值~最大值之间随机数

functionrandom(min, max) {return Math.floor(Math.random() * (max - min + 1) +min);
}

View Code

数组去重

//NO.1
Array.prototype.unique = function() {for(var i=0, len = this.length; i<len; i++) {for(var j=i+1; j<len; j++) {if(this[i] === this[j])this.splice(j, 1);}}return this;
};//["a","a","b"].unique();//NO.2
Array.prototype.unique = function(){var that = this, temp = {}, result =[];for(var i = 0, len = that.length; i < len; i++) {if(!temp[typeof (that[i])+that[i]]){result.push(that[i]);temp[typeof(that[i])+that[i]] = '1';}}returnresult;
}//["a","a","b"].unique();

View Code

数组快排

functionquickSort(arr) {if (arr.length < 2) {returnarr;}var pivotIndex = Math.floor(arr.length / 2);var pivot = arr.splice(pivotIndex, 1)[0];var left =[];var right =[];for (var i = 0, j = arr.length; i < j; i++) {if (arr[i] <pivot) {left.push(arr[i]);}else{right.push(arr[i]);}}returnquickSort(left).concat([pivot], quickSort(right));
}var test = quickSort([1,9,2,8,3,7,4,6,5]);

View Code

将arguments转换成数组

var arr = Array.prototype.slice.call(arguments, 0);

View Code

数组随机排序

var arr = [1, 2, 3, 4, 5];
arr.sort(function(){return (Math.random() - 0.5);
});

View Code

获取数组中最小/大值

var max = Math.max.apply(null, array);var min = Math.min.apply(null, array);

View Code

数组index

functionindex(t, arr){if(arr.indexOf){returnarr.indexOf(t);}for(var i = arr.length ; i--; ){if(arr[i]===t){return i*1;}}return -1;
}

View Code

多维数组转一维数组

functionarr2ToArr(arr){return arr.toString().split(",");
}

View Code

选择数组中两数之和等于某值的情况 

//NO.1
var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], result = [], count = 10;for(var i = 0, len = arr.length; i < len; i ++){for(var j = i + 1; j < len; j ++){if(arr[i] + arr[j] ===count){result.push([arr[i], arr[j]]);}}
}//NO.2
var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], result = [], count = 10;for(var i = 0, len = Math.round(arr.length/2); i < len; i ++){if(arr.indexOf(count - arr[i]) !== -1){result.push([arr[i], count-arr[i]]);}
}

View Code

数字金额转换成大写

functiondigit_uppercase(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;}return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');
}

View Code

日期格式化

Date.prototype.toString=function(format,loc){var time={};time.Year=this.getFullYear();time.TYear=(""+time.Year).substr(2);time.Month=this.getMonth()+1;time.TMonth=time.Month<10?"0"+time.Month:time.Month;time.Day=this.getDate();time.TDay=time.Day<10?"0"+time.Day:time.Day;time.Hour=this.getHours();time.THour=time.Hour<10?"0"+time.Hour:time.Hour;time.hour=time.Hour<13?time.Hour:time.Hour-12;time.Thour=time.hour<10?"0"+time.hour:time.hour;time.Minute=this.getMinutes();time.TMinute=time.Minute<10?"0"+time.Minute:time.Minute;time.Second=this.getSeconds();time.TSecond=time.Second<10?"0"+time.Second:time.Second;time.Millisecond=this.getMilliseconds();time.Week=this.getDay();var MMMArrEn=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];var MMMArr=["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"];var WeekArrEn=["Sun","Mon","Tue","Web","Thu","Fri","Sat"];var WeekArr=["星期日","星期一","星期二","星期三","星期四","星期五","星期六"];var oNumber=time.Millisecond/1000;if(format!=undefined && format.replace(/\s/g,"").length>0){if(loc!=undefined && loc =="en"){MMMArr=MMMArrEn.slice(0);WeekArr=WeekArrEn.slice(0);}format=format.replace(/yyyy/ig,time.Year).replace(/yyy/ig,time.Year).replace(/yy/ig,time.TYear).replace(/y/ig,time.TYear).replace(/MMM/g,MMMArr[time.Month-1]).replace(/MM/g,time.TMonth).replace(/M/g,time.Month).replace(/dd/ig,time.TDay).replace(/d/ig,time.Day).replace(/HH/g,time.THour).replace(/H/g,time.Hour).replace(/hh/g,time.Thour).replace(/h/g,time.hour).replace(/mm/g,time.TMinute).replace(/m/g,time.Minute).replace(/ss/ig,time.TSecond).replace(/s/ig,time.Second).replace(/fff/ig,time.Millisecond).replace(/ff/ig,oNumber.toFixed(2)*100).replace(/f/ig,oNumber.toFixed(1)*10).replace(/EEE/g,WeekArr[time.Week]);}else{format=time.Year+"-"+time.Month+"-"+time.Day+" "+time.Hour+":"+time.Minute+":"+time.Second;}returnformat;
}var d=newDate();
console.log(d.toString());//2012-7-27 9:26:52
console.log(d.toString(""));    //2012-7-27 9:26:52
console.log(d.toString("yyyy-MM-dd HH:mm:ss"));    //2012-07-27 09:26:52
console.log(d.toString("yyyy年MM月dd日 HH:mm:ss"));    //2012年07月27日 09:26:52
console.log(d.toString("yyyy-MM-dd HH:mm:ss fff"));    //2012-07-27 09:26:52 237
console.log(d.toString("yyyy年 MMM dd EEE"));    //2012年 七月 27 星期五
console.log(d.toString("yyyy MMM dd EEE","en"));    //2012 Jul 27 Fri

View Code

五种继承方式

//构造函数的继承的五种方式
functionAnimal() {this.species = "dong wu";
}//NO.1 构造函数绑定
functionCat(name, color) {Animal.apply(this, arguments);this.name =name;this.color =color;
}//NO.2 prototype模式
functionCat (name, color) {this.name =name;this.color =color;
}
Cat.prototype= newAnimal();
Cat.prototype.constructor=Cat;//NO.3 直接继承prototype
functionCat(name, color) {this.name =name;this.color =color;
}
Cat.prototype=Animal.prototype;
Cat.prototype.constructor=Cat;//NO.4 利用空对象做中介
functionCat(name, color) {this.name =name;this.color =color;
}functionF(){}
F.prototype=Animal.prototype;Cat.prototype= newF();
Cat.prototype.constructor=Cat;//NO.5 拷贝继承
functionCat(name, color) {this.name =name;this.color =color;
}functionextend(Child, Parent) {var p =Parent.prototype;var c =Child.prototype;for (var i inp) {c[i]=p[i];}c.uber=p;
}
extend(Cat, Animal);

View Code

根据生日算年龄

functiongetAge(dateString) {var today = newDate();var birthDate = newDate(dateString);var age = today.getFullYear() -birthDate.getFullYear();var m = today.getMonth() -birthDate.getMonth();if (m < 0 || (m === 0 && today.getDate() <birthDate.getDate())) {age--;}returnage;
}
console.log(getAge("1990,1,12"));

View Code

事件绑定

var events = (function(win){//事件绑定functionon(el, ev, fn){if(el.addEventlistener){on= function(el, ev, fn) {el.addEventlistener(ev, fn,false);};}else if(el.attachEvent){on= function(el, ev, fn){el.attachEvent('on' + ev, function(){fn.call(el);//IE This
});};}else{on= function(el, ev, fn){el['on' + ev] =fn;};}on(el, ev, fn);}//解除事件绑定functionoff(el, ev, fn){if(el.removeEventlistener){off= function(el, ev, fn) {el.removeEventlistener(ev, fn,false);};}else if(el.detachEvent){off= function(el, ev, fn){el.detachEvent('on' +ev, fn);};}else{off= function(el, ev){el['on' + ev] = null;};}off(el, ev, fn);}//获取事件对象functiongetEvent(ev){return ev ||win.event;}//获取事件目标functiongetTarget(ev){return ev.target ||ev.srcElement;}//获取键值functiongetKeyCode(ev){if (typeof ev.charCode == 'number'){getKeyCode= function(ev){returnev.charCode;};}else{getKeyCode= function(ev){returnev.keyCode;};}getKeyCode(ev);}//阻止默认行为functionpreventDefault(ev){if(ev.preventDefault){preventDefault= function(ev){ev.preventDefault();};}else{preventDefault= function(ev){ev.returnValue= false;};}preventDefault(ev);}//阻止冒泡functionstopPropagation(ev){if(ev.stopPropagation){stopPropagation= function(ev){ev.stopPropagation();};}else{stopPropagation= function(ev){ev.cancelBubble= true;};}stopPropagation(ev);}return{on: on,off: off,getEvent: getEvent,getTarget: getTarget,getKeyCode: getKeyCode,preventDefault: preventDefault,stopPropagation: stopPropagation};
}(window));

View Code

自定义事件

var EventHandlers ={events: {},fire:function(ev, arg){if(this.events[ev]){var e = this.events[ev];for(var i = 0, len = e.length; i < len; i++){e[i](arg);}}},on:function(ev, fn){if(!this.events[ev]){this.events[ev] =[];}this.events[ev].push(fn);},off:function(ev, fn){if(this.events[ev]){var e = this.events[ev];for(var i = 0, len = e.length; i < len; i++){if(e[i] ==fn){e.splice(i,1);break;}}}}
};

View Code

加载获取图片尺寸

var img = newImage();
img.onload= function() {console.log(this.width + 'x' + this.height);
}

View Code

Object.create

var create = Object.create || function(o){var F = function(o){};F.prototype=o;return newF;
};

View Code

Object.prototype.bind

var bind = Object.prototype.bind || function(scope) {var fn = this;return function() {returnfn.apply(scope);};
};

View Code

设置选定文本

//选定文本
functionsetSelectText(text, start, num) {if(text.setSelectionRange) {text.setSelectionRange(start,num);text.focus();}else if(text.createTextRange) {var range =text.createTextRange();range.collapse(true);range.moveStart('character',start);range.moveEnd('character',num - start);                //用最后的位置 - 开始的位置 = 个数
range.select();}
}

View Code

获取选择文本

functiongetSelectedText(id){var o =document.getElementById(id);if(window.getSelection) {if(o.selectionStart != undefined && o.selectionEnd !=undefined){returno.value.substring(o.selectionStart, o.selectionEnd);}}else{returndocument.selection.createRange().text;}
}

View Code

在光标位置插入字符串

//光标位置插入字符串
functioninsertHtmlAtCursor(id, text){var o =document.getElementById(id);if(document.selection){o.focus();document.selection.createRange().text=text;o.focus();}else if(o.selectionStart) {var start = o.selectionStart, end =o.selectionEnd;o.value= o.value.substring(0, start) + text +o.value.substring(end, o.value.length);}
}

View Code

在url中查找指定参数的值

functiongetQuery(){var s = (location.search.length > 0 ? location.search.substring(1) : ''),res={},items= s.length ? s.split('&') : [],item= null, name = null, value = null,i, len=items.length;for (i = 0; i < len; i++){item= items[i].split('=');name= decodeURIComponent(item[0]);value= decodeURIComponent(item[1]);if(name.length){res[name]=value;}}returnres;
}

View Code

IE6里a:hover图片缓存

document.execCommand("BackgroundImageCache",false,true);

View Code

反转文本顺序

String.prototype.reverse = function(){if(this.length < 2){return this;}var str = this.split(''), result = '', len = this.length - 1;while(len >= 0){result+= this[len];len--;}returnresult;
}'反转文本顺序'.reverse();

View Code

清除空格

String.prototype.trim = String.trim || function() {return this.replace(/^\s*(.*?)\s+$/, "$1")
};

View Code

加入收藏

functionaddFavorite(url, title) {try{window.external.addFavorite(url, title);}catch(e) {try{window.sidebar.addPanel(title, url,"");}catch(e) {alert("加入收藏失败,请使用Ctrl+D进行添加");}}
}

View Code

设为首页

functionsetHomepage(url) {if(document.all) {document.body.style.behavior= 'url(#default#homepage)';document.body.setHomePage(url)}else if(window.sidebar) {if(window.netscape) {try{netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect")}catch(e) {alert("该操作被浏览器拒绝,如果想启用该功能,请在地址栏内输入 about:config,然后将项 signed.applets.codebase_principal_support 值该为true")}}var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);prefs.setCharPref('browser.startup.homepage', url)}
}

View Code

insertAfter

functioninsertAfter(newChild,refChild){var parElem=refChild.parentNode;if(parElem.lastChild==refChild){refChild.appendChild(newChild);}else{parElem.insertBefore(newChild,refChild.nextSibling);}
}

View Code

innerText操作

//获取innertext
functiongetInnerText(element) {if (typeof element.textContent == 'string') {returnelement.textContent;}else{returnelement.innerText;}
}//设置innertext
functionsetInnerText(element, text) {if (typeof element.textContent == 'string') {element.textContent=text;}else{element.innerText=text;}
}

View Code

获取offsetTop

//获取offsetTop
functionoffsetTop(element) {var top = element.offsetTop;        //第一层的距离var parent =element.offsetParent;while (parent !== null) {top+=parent.offsetTop;parent=parent.offsetParent;}returntop;
}

View Code

构建字符串的最优方法

var arr = ['item 1', 'item 2', 'item 3', ...];var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>';

View Code

获取字符串中出现次数最多的字符 

//NO.1
String.prototype.strCount = function(){var num = 0, val = '', result = null, temp = '', that = this;while(that) {temp=that;val= that.substr(0, 1);that= that.replace(new RegExp(val, "g"), "");if (temp.length - that.length >num) {num= temp.length -that.length;result={val:val, num: num};}}returnresult;
};//NO.2
String.prototype.strCount = function(){var obj = {}, num = 0, val = '';for(var i = 0, len = this.length; i < len; i+=1){if(!obj[this[i]]){obj[this[i]] =[];}obj[this[i]].push(this[i]);}for(var arr inobj){if(num <obj[arr].length){num=obj[arr].length;val= obj[arr][0];}}return{val:val, num: num};
};//NO.3
functionstrCount(str){var o = {}, ret = {name: '', num: 0};for(var i = 0, len = str.length; i < len; i++){if( o[str[i]] ) {o[str[i]]++;}else{o[str[i]]= 1;}if(ret.num <o[str[i]]){ret.name=str[i];ret.num=o[str[i]];}}returnret;}//NO.4
functionstrCount(str){var ret = {name: '', num: 0};str.split('').sort().join('').replace(/(\w)\1+/g, function($0, $1){if ( ret.num < $0.length ) {ret.num= $0.length;ret.name= $1;}});returnret;
}

View Code

对象深度clone 

var cloneObj = function(obj){varnewobj, s;if(typeof obj !== 'object'){return;}newobj= obj.constructor === Object ?{} : [];if(window.JSON){s= JSON.stringify(obj), //系列化对象newobj = JSON.parse(s); //反系列化(还原)}else{if(newobj.constructor ===Array){newobj.concat(obj);}else{for(var i inobj){newobj[i]=obj[i];}}}returnnewobj;
};

View Code

千分位表示

//NO.1
functionmillesimal(v){var num = v.length%3, prev = '', next = v.substring(num), arr =[];if(num !== 0){prev= v.substring(0, num);arr.push(prev);}for(var i = 0, len = next.length; i < len; i += 3){arr.push(next.substr(i,3))}returnarr.join();
}//NO.2
functionmillesimal(v){return v.toString().replace(/(?=(?!\b)(\d{3})+$)/g, ',');
}//NO.3
functionmillesimal(v){return v.toString().replace(/\B(?=(\d{3})+$)/g, ',');
}

View Code

替换全部

String.prototype.replaceAll = function(s1, s2) {return this.replace(new RegExp(s1, "gm"), s2)
}

View Code

HTML转义

//转义html标签
functionHtmlEncode(text) {return text.replace(/&/g, '&amp').replace(/\"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
}//还原html标签
functionHtmlDecode(text) {return text.replace(/&amp;/g, '&').replace(/&quot;/g, '\"').replace(/&lt;/g, '<').replace(/&gt;/g, '>')
}

View Code

随机字符串(字母&数字)

functionrandomStringNum(len) {var ret = "";for( ; ret.length < len; ret += Math.random().toString(36).substr(2));return ret.substr(0, len);
}

View Code

随机颜色 

//(0xffffff+1) 表示颜色最大值(0x000000 ~ 0xffffff+1)//<<0             表示左移一位,将颜色16进制的颜色值转成整型//toString(16) 表示再将整型的颜色值转成16进制//slice(-6)     表示生成的16进制值少于6位时,首尾依次补0
var getRandomColor = function(){return '#'+('00000'+(Math.random()*(0xffffff+1)<<0).toString(16)).slice(-6);
};

View Code

curry

functioncurrying(fn) {var args = [].slice.call(arguments, 1);return function() {var newArgs =args.concat([].slice.call(arguments));return fn.apply(null, newArgs);}
}//use
var test = currying(function() {console.log(arguments);
},'a');test(1);

View Code

uncurrying

Function.prototype.uncurrying = function(){var self = this;return function(){returnFunction.prototype.call.apply(self, arguments);}
};

View Code

函数节流

//函数节流
var throttle = function(fn, interval){var self =fn,timer,firstTime= true;return function(){var args =arguments,that= this;if(firstTime){self.apply(that, args);return firstTime = false;}if(timer){return false;}timer= setTimeout(function(){clearTimeout(timer);timer= null;self.apply(that, args);}, interval|| 500);};
};

View Code

分时调用

/*** [timeChunk 分时调用]* @param  {[type]}   arr   [数据]* @param  {Function} fn    [处理函数]* @param  {[type]}   count [执行次数]*/
var timeChunk = function(arr, fn, count){var obj, t, len =arr.length;var start = function(){for (var i = 0, obj; i < Math.min(count || 1, arr.length); i++){obj=arr.shift();fn(obj);}};return function(){t= setInterval(function(){if (arr.length === 0){returnclearInterval(t);}start();},200);};
};

View Code

单例模式抽象

//单例模式抽象
var getSingle = function(fn){varres;return function(){return res || (res = fn.apply(this, arguments)); }
};

View Code

转载于:https://www.cnblogs.com/jununx/p/3612280.html

JavaScript代码片段相关推荐

  1. 收集 48 个 JavaScript 代码片段,仅需 30 秒就可理解(值得收藏)

    该项目来自于 Github 用户 Chalarangelo,目前已在 Github 上获得了 5000 多Star,精心收集了多达 48 个有用的 JavaScript 代码片段,该用户的代码可以让程 ...

  2. 第一百一十八期:运行 JavaScript 代码片段的 20 种工具

    运行 JavaScript 代码片段的 20 种工具 前端日常开发中,我们使用喜爱的 IDE 调试 JavaScript 代码,比如我喜欢的代码编辑器有两个,Sublime Text 3 和 VS C ...

  3. 精心收集的 48 个 JavaScript 代码片段,仅需 30 秒就可理解!

    点击上方"CSDN",选择"置顶公众号" 关键时刻,第一时间送达! 该项目来自于 Github 用户 Chalarangelo,目前已在 Github 上获得了 ...

  4. JavaScript 代码片段

    近期在GitHub上看到一位叫Chalarangelo的用户写了一篇30 秒就能理解的 JavaScript 代码片段,很多人都在看,下面分享一些他的JS用法. 给定一个 key 和一个 set 作为 ...

  5. 【JS】1070- 8个工程必备的JavaScript代码片段(建议添加到项目中)

    8个工程必备的JavaScript代码片段,听过这样起博客标题可以提高阅读量.???? 最近写博客好累,让8月征文活动搞的,今天水一篇好了,麻烦不要给我点赞,不想看到消息通知的小红点. 1. 获取文件 ...

  6. 16个工程必备的JavaScript代码片段

    作者:_红领巾 https://juejin.cn/post/7000919400249294862 1. 下载一个excel文档 同时适用于word,ppt等浏览器不会默认执行预览的文档,也可以用于 ...

  7. 8个工程必备的JavaScript代码片段(建议添加到项目中)

    点击上方 前端瓶子君,关注公众号 回复算法,加入前端编程面试算法每日一题群 8个工程必备的JavaScript代码片段,听过这样起博客标题可以提高阅读量.???? 最近写博客好累,让8月征文活动搞的, ...

  8. angular 多个片段拼接_10个JavaScript代码片段,帮助你成为更好的开发者

    毫无疑问,JavaScript是Web开发中最流行的编程语言之一.无论你使用的是React,Vue还是Angular,它们都属于JavaScript.JS围绕着广阔而至关重要的生态系统发展,提供了许多 ...

  9. 加入收藏代码_100个原生JavaScript代码片段知识点详细汇总【实践】

    作者:小棋子js 转发链接:https://www.jianshu.com/p/b5171efa340f JavaScript 是目前最流行的编程语言之一,正如大多数人所说:"如果你想学一门 ...

最新文章

  1. python3 中的编码问题 unicode, utf-8, gbk, ascii
  2. python之time和datetime的常用方法
  3. C# ThreadPool类(线程池)
  4. 北京奥运会闭幕式落下帷幕
  5. Linux常用端口查询命令及常见端口和端口分类
  6. CSS基本选择器、层次选择器、结构伪类选择器、属性选择器
  7. NetBeans 时事通讯(刊号 # 60 - Jun 21, 2009)
  8. 安装完成后在命令行运行bash时报错0x80070057
  9. Master PDF editor在ubuntu下面的配置
  10. 每个tabpage中都有一个dategridview_其实每个人都是一个孩子,仅此而已
  11. JS之数据类型v(** v**)v个人笔记
  12. STM32 串口接收流程-串口接收中断
  13. 2020年最值得关注的28款区块链游戏
  14. Adobe Photoshop Pro CC 2019及类似软件注册
  15. 用EEupdate修改Intel网卡类型
  16. 2016年个人总结报告PPT(刘欣)
  17. Java添加一个滑动验证码,有啥可难的,分分钟加一个
  18. 佳能打印机HP打印机爱普生打印机提示卡纸了确找不到卡纸
  19. 清明时节——《荒原的呼唤》选载之三
  20. CRM客户关系管理系统源码跟单销售公司订单跟进客户公海合同管理办公erp客户管理(小程序+APP+H5)

热门文章

  1. 113. 路径总和 II golang
  2. mysql 学习笔记15 子查询
  3. C++ 普通函数与函数模板 区别以及调用规则01
  4. [STL]List的实现
  5. request mysql 接口_TP5接口开发
  6. linux 信号signal和sigaction理解
  7. Java读写二维数组到文件
  8. 最新BAT大厂面试者整理的Android面试题目模板,分享PDF高清版
  9. jQuery的事件绑定和解绑
  10. Java构造函数的深入理解