JavaScript代码片段

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

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

JavaScript动态加载

//NO.1
function loadScript(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
function loadScript(url, callback){var xhr = new XMLHttpRequest();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加载完执行

function domLoad(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);
function insertRule(sheet, selectorText, cssText, position) {if (sheet.insertRule) {sheet.insertRule(selectorText + ' { ' + cssText + ' }', position);} else if (sheet.addRule) {sheet.addRule(selectorText, cssText, position);}
}//删除第一条规则
//deleteRule(sheet, 0);
function deleteRule(sheet, position) {if (sheet.deleteRule) {sheet.deleteRule(position);} else if (sheet.removeRule) {sheet.removeRule(position);}
}
View Code

加载样式表

function addSheet(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样式

function getStyle(o, attr){if(o.currentStyle){return o.currentStyle[attr];}else{return getComputedStyle(o,false)[attr];}
}
View Code

getByClass

function getElementsByClassName(classname, parent, nodename) {var parent = parent || document, nodename = nodename || "*";if(parent.getElementsByClassName){return parent.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]);}}}return res;} ();}
}
View Code

hasClass

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

addClass

function addClass(element, cName) {if (!hasClass(element, cName)) {element.className += ' ' + cName;}
}
View Code

removeClass

function removeClass(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>
function fnCall(info){// 在前台提供一个方法fnCall的方法// http://www.xxx.com?name=fnCall 在(后台/其他页面)自动获取fnCall的名字并且执行
}
</script>
View Code

获取服务器时间

function getNowDate(callback){var xhr = new XMLHttpRequest();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操作

function Cookie(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)){var date;if(typeof options.expires == 'number'){date = new Date();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;}}}return cookValue;}
}
//设置
Cookie("user", "Jununx");
//获取
Cookie("user");
//删除
Cookie("user", null);
View Code

base64编码解码 

function b64Encode(str) {return btoa(unescape(encodeURIComponent(str)));
}function b64Decode(str) {return decodeURIComponent(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

阶乘缓存

function memfactorial(n){if(!memfactorial.cache){memfactorial.cache = {"0" : 1,"1" : 1};}if(!memfactorial.cache.hasOwnProperty(n)){memfactorial.cache[n] = n * memfactorial(n - 1);}return memfactorial.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 ++;}}return b;}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 ++;}}return b;}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;}}return b;}else{return 0;}
};// NO.4
String.prototype.sLen = function(){var s = this.replace(/[^\x00-\xff]/g, "**");return s.length;
};
View Code

判断数据类型

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

获取窗口位置

function sereen(){return {left : window.screenLeft || window.scrollX,top : window.screenTop || window.scrollY};
}
View Code

获取可视窗口大小

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

获取scrollTop

function getScrollTop(){if(typeof pageYOffset!= 'undefined'){return pageYOffset;} 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

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

function random(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';}}return result;
}
// ["a","a","b"].unique();
View Code

数组快排

function quickSort(arr) {if (arr.length < 2) {return arr;}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]);}}return quickSort(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

function index(t, arr){if(arr.indexOf){return arr.indexOf(t);}for(var i = arr.length ; i--; ){if(arr[i]===t){return i*1;}}return -1;
}
View Code

多维数组转一维数组

function arr2ToArr(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

数字金额转换成大写

function digit_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;}return format;
}var d=new Date();
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

五种继承方式

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

根据生日算年龄

function getAge(dateString) {var today = new Date();var birthDate = new Date(dateString);var age = today.getFullYear() - birthDate.getFullYear();var m = today.getMonth() - birthDate.getMonth();if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {age--;}return age;
}
console.log(getAge("1990,1,12"));
View Code

事件绑定

var events = (function(win){// 事件绑定function on(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);}// 解除事件绑定function off(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);}// 获取事件对象function getEvent(ev){return ev || win.event;}// 获取事件目标function getTarget(ev){return ev.target || ev.srcElement;}// 获取键值function getKeyCode(ev){if (typeof ev.charCode == 'number'){getKeyCode = function(ev){return ev.charCode;};} else {getKeyCode = function(ev){return ev.keyCode;};}getKeyCode(ev);}// 阻止默认行为function preventDefault(ev){if(ev.preventDefault){preventDefault = function(ev){ev.preventDefault();};} else {preventDefault = function(ev){ev.returnValue = false;};}preventDefault(ev);}// 阻止冒泡function stopPropagation(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 = new Image();
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 new F;
};
View Code

Object.prototype.bind

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

设置选定文本

//选定文本
function setSelectText(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

获取选择文本

function getSelectedText(id){var o = document.getElementById(id);if(window.getSelection) {if(o.selectionStart != undefined && o.selectionEnd != undefined){return o.value.substring(o.selectionStart, o.selectionEnd);}}else{return document.selection.createRange().text;}
}
View Code

在光标位置插入字符串

// 光标位置插入字符串
function insertHtmlAtCursor(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中查找指定参数的值

function getQuery(){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;}}return res;
}
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 --;}return result;
}'反转文本顺序'.reverse();
View Code

清除空格

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

加入收藏

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

设为首页

function setHomepage(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

function insertAfter(newChild,refChild){var parElem=refChild.parentNode;if(parElem.lastChild==refChild){refChild.appendChild(newChild);}else{parElem.insertBefore(newChild,refChild.nextSibling);}
}
View Code

innerText操作

//获取innertext
function getInnerText(element) {if (typeof element.textContent == 'string') {return element.textContent;} else {return element.innerText;}
}
//设置innertext
function setInnerText(element, text) {if (typeof element.textContent == 'string') {element.textContent = text;} else {element.innerText = text;}
}
View Code

获取offsetTop

//获取offsetTop
function offsetTop(element) {var top = element.offsetTop;        //第一层的距离var parent = element.offsetParent;while (parent !== null) {top += parent.offsetTop;parent = parent.offsetParent;}return top;
}
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};}}return result;
};// 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 in obj){if(num < obj[arr].length){num = obj[arr].length;val = obj[arr][0];}}return {val:val, num: num};
};// NO.3
function strCount(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]];}}return ret;}// NO.4
function strCount(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;}});return ret;
}
View Code

对象深度clone 

var cloneObj = function(obj){var newobj, 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 in obj){newobj[i] = obj[i];}}}return newobj;
};
View Code

千分位表示

// NO.1
function millesimal(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))}return arr.join();
}// NO.2
function millesimal(v){return v.toString().replace(/(?=(?!\b)(\d{3})+$)/g, ',');
}// NO.3
function millesimal(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标签
function HtmlEncode(text) {return text.replace(/&/g, '&amp').replace(/\"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
}
// 还原html标签
function HtmlDecode(text) {return text.replace(/&amp;/g, '&').replace(/&quot;/g, '\"').replace(/&lt;/g, '<').replace(/&gt;/g, '>')
}
View Code

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

function randomStringNum(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

function currying(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(){return Function.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){return clearInterval(t);}start();}, 200);};
};
View Code

单例模式抽象

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

 

 

 

 

 

 

 

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/401900.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

路由器开发(一)—— 路由器硬件结构及软件体系

一、路由器的硬件构成 路由器主要由以下几个部分组成&#xff1a;输入/输出接口部分、包转发或交换结构部分&#xff08;switching fabric&#xff09;、路由计算或处理部分。如图所示 图1 路由器的基本组成 输入端口是物理链路和输入包的进口处。端口通常由线卡提供&#…

路由器开发(二)—— 路由器工作原理

当信息需要在两个网络之间传输时&#xff0c;常用路由器这种互连设备来负责数据的传输。路由器的主要工作是&#xff1a;路径的决定和数据包的转发&#xff08;从路由器一个接口输入&#xff0c;然后选择合适接口输出&#xff09;&#xff1b;维护路由表。 路由器工作的方式非常…

Android颜色渐变的分隔线(ListView)

2019独角兽企业重金招聘Python工程师标准>>> shape.xml xx <?xml version"1.0" encoding"utf-8"?><shape xmlns:android"http://schemas.android.com/apk/res/android" > <gradient android:startColor&qu…

项目实践中Linux集群的总结和思考

2019独角兽企业重金招聘Python工程师标准>>> 前言&#xff1a;作为一名Linux/unix系统工程师、项目实施工程师&#xff0c;这几年一直在涉及到对外项目&#xff0c;经手过许多小中型网站的架构&#xff0c;F5、LVS及Nginx接触的都比较多&#xff0c;我想一种比较通俗…

路由器基础知识详解

第一章 网络互联 网络的根本目的非常简单&#xff1a;方便人们交换所获得的信息。但是网络的应用需求非常复杂&#xff1a;有的用户希望高带宽&#xff0c;但并不要求很长的传输距离&#xff1b;有的用户要求很长的距离&#xff0c;但对带宽要求很低&#xff1b;有的对网络的…

事务与锁机制

2019独角兽企业重金招聘Python工程师标准>>> 事务定义&#xff1a; 访问并可能更新数据库&#xff1a;一句或一组SQL&#xff0c;或者是一段程序&#xff0c;反正update了就是事务 ACID的4原则&#xff1a; 原子性&#xff1a; 一致性&#xff1a; 隔离性&#xff1…

路由器 VS OSI七层模型

OSI Open Source Initiative&#xff08;简称OSI&#xff0c;有译作开放源代码促进会、开放原始码组织&#xff09;是一个旨在推动开源软件发展的非盈利组织。OSI参考模型&#xff08;OSI/RM&#xff09;的全称是开放系统互连参考模型&#xff08;Open System Interconnection …

Linux Wireless架构总结

1、无线网络驱动(ath9k_htc) ath9k_htc是一个基于USB接口的SoftMAC无线网络适配器。为了其驱动能正常工作&#xff0c;首先必须调用usb_register来注册驱动定义的usb_driver&#xff0c;以借助USB Core的力量来处理与USB协议相关的事件。其代码如下&#xff1a;[cpp] view plai…

MySQL 日志文件 说明

MySQL 5.5 官方文档上有关日志的分类&#xff1a;By default, nologs are enabled. The following log-specific sections provide information about the server options that enable logging.--默认情况下&#xff0c;没有启动任何log&#xff0c;可以通过如下log 选项来启动…

Linux 下wifi 驱动开发(四)—— USB接口WiFi驱动浅析

前面学习了SDIO接口的WiFi驱动&#xff0c;现在我们来学习一下USB接口的WiFi驱动&#xff0c;二者的区别在于接口不同。而USB接口的设备驱动&#xff0c;我们前面也有学习&#xff0c;比如USB摄像头驱动、USB鼠标驱动&#xff0c;同样都符合LinuxUSB驱动结构&#xff1a; USB设…

Linux 下wifi 驱动开发(三)—— SDIO接口WiFi驱动浅析

SDIO-Wifi模块是基于SDIO接口的符合wifi无线网络标准的嵌入式模块&#xff0c;内置无线网络协议IEEE802.11协议栈以及TCP/IP协议栈&#xff0c;能够实现用户主平台数据通过SDIO口到无线网络之间的转换。SDIO具有传输数据快&#xff0c;兼容SD、MMC接口等特点。 对于SDIO接口的w…

Erlang并发机制 –进程调度

2019独角兽企业重金招聘Python工程师标准>>> Erlang调度器主要完成对Erlang进程的调度&#xff0c;它是Erlang实现软件实时和进程之间公平使用CPU的关键。Erlang运行时&#xff0c;有4种任务需要被调度&#xff1a;进程&#xff0c;Port&#xff0c;Linked-in drive…

Linux 下wifi 驱动开发(二)—— WiFi模块浅析

一、什么是wifi 模块 百度百科上这样定义&#xff1a; Wi-Fi模块又名串口Wi-Fi模块&#xff0c;属于物联网传输层&#xff0c;功能是将串口或TTL电平转为符合Wi-Fi无线网络通信标准的嵌入式模块&#xff0c;内置无线网络协议IEEE802.11b.g.n协议栈以及TCP/IP协议栈。传统的硬件…

Linux 下wifi 驱动开发(一)—— WiFi基础知识解析

一、WiFi相关基础概念 1、什么是wifi 我们看一下百度百科是如何定义的&#xff1a; Wi-Fi是一种可以将个人电脑、手持设备&#xff08;如pad、手机&#xff09;等终端以无线方式互相连接的技术&#xff0c;事实上它是一个高频无线电信号。[1] 无线保真是一个无线网络通信技术…

Linux 网络设备驱动开发(一) —— linux内核网络分层结构

Linux内核对网络驱动程序使用统一的接口&#xff0c;并且对于网络设备采用面向对象的思想设计。 Linux内核采用分层结构处理网络数据包。分层结构与网络协议的结构匹配&#xff0c;既能简化数据包处理流程&#xff0c;又便于扩展和维护。 一、内核网络结构 在Linux内核中&#…

Linux 网络设备驱动开发(二) —— Linux 网络栈剖析

一、协议简介 虽然对于网络的正式介绍一般都参考了 OSI&#xff08;Open Systems Interconnection&#xff09;模型&#xff0c;但是本文对 Linux 中基本网络栈的介绍分为四层的 Internet 模型&#xff08;如图 1 所示&#xff09;。 图 1. 网络栈的 Internet 模型 这个栈的最底…

Linux 网络设备驱动开发(三) —— 网络设备驱动基本原理和框架

一、协议栈层次对比 二、Linux网络子系统 Linux网络子系统的顶部是系统调用接口层。它为用户空间提供的应用程序提供了一种访问内核网络子系统的方法&#xff08;socket&#xff09;。位于其下面是一个协议无关层&#xff0c;它提供一种通用的方法来使用传输层协议。然后是具…

国产杀毒软件也开始支持虚拟化

今天不小心看到一个较老的“新”闻&#xff0c;国产安全软件厂商瑞星已经推出支持VMware vshield Endpoint技术的防病毒产品&#xff0c;也就是说如果客户今天使用的是VMware的虚拟化软件&#xff0c;上面运行的所有虚拟机就不需要安装传统的防病毒软件程序&#xff0c;而可以直…

VRP平台基本操作

一、显示系统信息 <Huawei>display version 图上所示可以知道VRP平台信息&#xff0c;运行的版本&#xff0c;运行的时间 二、修改和查看设备系统时间参数 1.查看时间 <Huawei>display clock 2.修改系统日期和时间 三、进入系统视图界面 <Huawei>system-view…

Android中获取应用程序(包)的信息-----PackageManager的使用(一)

本节内容是如何获取Android系统中应用程序的信息&#xff0c;主要包括packagename、label、icon、占用大小等。具体分为两个 部分&#xff0c;计划如下&#xff1a; 第一部分&#xff1a; 获取应用程序的packagename、label、icon等 &#xff1b; 第二部分&#xff1a; 获取应用…