javascript两段代码,两个小技巧


第一段代码就是强调一下这个用法,我在我的项目中使用了一个switch,后来我发现这样的代码好丑,于是我就写成||&&形式的, 后来测试性能的时候,发现性能竟然上了一个数量级,可见这种写法在某些情况下可以增加性能,但是我并不确定是何种情况才能提高性能,因为我测试在通常情况下switch和||&&的性能是差不多的.
原来的代码:
复制代码 代码如下:

switch(this.now_char=this.str.charAt(this.index)){
case "/":
if(this.handleNote()) continue;else this.str2+=this.now_char;
break;
case "\"":
case "\'":
if(this.handleStr()) continue;else this.str2+=this.now_char;
break;
case "\n":
if(this.handleLine()) continue;else this.str2+=this.now_char;
break;
case "{":
case "}":
if(this.handleDepth()) continue;else this.str2+=this.now_char;
break;
case ":":if(this.handleJson()) continue;else this.str2+=this.now_char;break;
default:
if(this.handleKeyword()) continue;else this.str2+=this.now_char;
break;
}

改写后的代码,功能当然是一样的 view sourceprint?1 (this.now_char=="/"&&(this.handleNote()||(this.str2+=this.now_char)))||
((this.now_char=="\""||this.now_char=="\'")&&(this.handleStr()||(this.str2+=this.now_char)))||
(this.now_char=="\n"&&(this.handleLine()||(this.str2+=this.now_char)))|| ((this.now_char=="{"||this.now_char=="}")&&(this.handleDepth()||(this.str2+=this.now_char)))||
(this.handleKeyword()||(this.str2+=this.now_char))
我嚼的第二种写法更简洁点,||&&还有很多用处,可以看那篇文章的介绍
第二段代码是利用了一个特性: (ele=document.createElement("div")) ;//这个表达式会返回一个dom元素,赋值的同时会把值返回给外边的括号
于是出来下面这段代码 :
复制代码 代码如下:

var mixin=function(target,options){
for(var i in options){
target[i]=options[i]
}
}
var ele=null;
mixin(ele=document.createElement("div"),{
id:"aa",
className:"bb",
innerHTML:"sss"
})
document.body.appendChild(ele)
debug(ele.id)//aa
debug(ele.className)//bb
debug(ele.innerHTML)//sss

这段代码是因为我实在厌烦了建立一个dom元素的时候的一大堆语句:
复制代码 代码如下:

var ele=document.createElement("div")
ele.id="aa";
ele.className="aa"
ele.innerHTML="sss"

等等等等,好烦啊.
于是出来了上面的代码.
用上面的原理还可以这样写代码 (ele=document.createElement("div")).className="aa"; 感觉是不是节省了一点空间呢,上面这句话节省了一个变量名,呵呵.
« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3