您好,欢迎访问一九零五行业门户网

javascript两段代码,两个小技巧_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; 感觉是不是节省了一点空间呢,上面这句话节省了一个变量名,呵呵.
其它类似信息

推荐信息