技巧一之setTimeout.
應用案例:比如你想一個函數循環執行10次,怎么辦?以前通常是先setInterval,然后clearInterval,技巧一就是克服這個問題
(function () {
var i = 0;
function job() {
console.log(i++);
if (i < 10) {
setTimeout(job, 1000);
}
}
job();
})();
技巧二之高效的for循環
應用案例:拋棄傳統的循環方式
(function () {
var arr=[];
for(var i=arr.length;i--;){
doStuff();
}
})();
這個方式為什么高效?
一:少了一個參數l=arr.length;
二:for語句中間那個玩意少進行了一次計算,以前的話是for(i=0;i<l;i++)這樣的話中間的語句會先比較i<l 然后比較出來的結果在
跟true 或者false比較,自然多了次計算
技巧三之高效賦值
應用案例:拋棄傳統的if判斷賦值
var i=1,ret;
ret=i!==1||true;
console.log(ret);
技巧四之強悍的簡短的attr
應用案例:setAttribute,getAttribute.這個方法不僅可以設置標準的屬性,還可以設置任意屬性,兼容好
function attr(elem, name, value) {
var ret;
if (value) {
if (/msie [6-7].0/i.test(navigator.userAgent)) {
ret = elem.getAttributeNode(name);
if (!ret) { //ie6 7不合法的屬性設置捕鳥,通過這里可以設置
ret = document.createAttribute(name);
elem.setAttributeNode(ret);
}
ret.nodeValue = value + "";
} else {
elem.setAttribute(name, value);
}
return elem;
} else { //ie6 7有得屬性獲取不鳥
ret = elem.getAttribute(name);
fixIe = elem.getAttributeNode(name).nodeValue;
ret = ret ? ret : fixIe ? fixIe : undefined;
return ret;
}
}
以上方法如何測試呢?
attr(document.getElementById("test"), "classxx", "xx")
alert(attr(document.getElementById("test"),"classxx"));
技巧五之getElementsByClassName.
應用案例 :以前js沒什么框架的時候,大家都再模仿這個方法,看看今天我是怎么高效的模仿出它來.這也不愧是js初學者的經典代碼
(function () {
var getElementsByClassName=function(cls,context){
var root = context || document;
return document.querySelectorAll ? root.querySelectorAll("." + a) : root.getElementsByClassName ?
root.getElementsByClassName(a) : help("*", cls, context);
}
var help=function(tagName,cls,context){
var root= context || document,
ret=[],elems,i,
rcls=new RegExp("^|s+"+cls+"s+|___FCKpd___4quot;);
elems = c.getElementsByTagName(tagName || "*");
for(i=elems.length;i--;){
if(rcls.test(elem[i].className)){
ret.push(elems[i]);
}
}
return ret;
}
})();
以上幾個js淫蕩技巧還是蠻實用的,前提是你沒用使用別人的js框架,用原生創造效率為前提的代碼.
還是那句話js代碼愛好者nothing原創,謝謝大家支持,覺得寫得好可以頂下,或者把鏈接發給朋友
來源:博客園,作者博客:http://nothingbrother.cnblogs.com/