当前位置: 首页 > 图文教程 > 网络编程 > Javascript > javascript两段代码,两个小技巧

Javascript
JS 参数传递的实际应用代码分析
prototype与jquery下Ajax实现的差别
用JS写的简单的计算器实现代码
javascript 数组操作实用技巧
JavaScript 中级笔记 第二章
JavaScript 中级笔记 第三章
JavaScript 中级笔记 第四章 闭包
JavaScript 中级笔记 第五章 面向对象的基础
Mootools 1.2教程 函数
Mootools 1.2教程 事件处理
通过Mootools 1.2来操纵HTML DOM元素
Mootools 1.2教程 设置和获取样式表属性
Mootools 1.2教程 输入过滤第一部分(数字)
Mootools 1.2教程 输入过滤第二部分(字符串)
Mootools 1.2教程 Fx.Tween的使用
Mootools 1.2教程 Fx.Morph、Fx选项和Fx事件
MooTools 1.2中的Drag.Move来实现拖放
Mootools 1.2教程 正则表达式
Mootools 1.2教程 定时器和哈希简介
Mootools 1.2教程 滚动条(Slider)

Javascript 中的 javascript两段代码,两个小技巧


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2010-02-27   浏览: 198 ::
收藏到网摘: n/a

话说以前我转过一片文章,讲的是 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"; 感觉是不是节省了一点空间呢,上面这句话节省了一个变量名,呵呵.