当前位置: 首页 > 图文教程 > 网络编程 > Javascript > Javascript 篱式条件判断

Javascript
Add a Table to a Word Document
Add Formatted Text to a Word Document
用jscript实现新建word文档
用jscript实现新建和保存一个word文档
Open and Print a Word Document
Use Word to Search for Files
Convert Seconds To Hours
Sample script that deletes a SQL Server database
Sample script that displays all of the users in a given SQL Server DB
firefox中用javascript实现鼠标位置的定位
div+css实现鼠标放上去,背景跟图片都会变化。
Locate a File Using a File Open Dialog Box
Save a File Using a File Save Dialog Box
用jscript实现列出安装的软件列表
List the Stored Procedures in a SQL Server database
Display SQL Server Login Mode
Display SQL Server Version Information
List all the Databases on a SQL Server
用jscript启动sqlserver
Stop SQL Server

Javascript 篱式条件判断


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 307 ::
收藏到网摘: n/a

我们已经知道,null 没有任何的属性值,并且无法获取其实体(existence)值。所以 null.property 返回的是错误(error)而不是 undefined 。 考虑下面的代码
if (node.nextSibling.className == ...) {
...
}
在 node 或者 node.nextSibling 为空(null)的情况下,会返回错误(error)。所以,通常情况下的解决方案的代码为
if ((node) && (next = node.nextSibling) && ... ) {
...
}
那么,当条件判断一多的情况下,代码会形成下面的情况
if (
(node) &&
(node.nextSibling) &&
(node.nextSibling.className == ...)
... ) {
...
}
随着判断条件的不断的增加,代码会变得非常的“丑陋”。
有个小的“伎俩”,可以简化条件判断表达式。我们可以增加个空对象({})或者零(0)作为替代
if ( next = (node || 0).nextSibling) ) {
...
}
那么,上述的代码就可以这样写
if (((node || 0).nextSibling || 0).className == ...) {
...
}
--Split--
就个人而言,上述的从某种角度而言,代码会非常的精简。但日常实际的编码过程中,尤其是多人配合的情况下,这些代码可能会给其他开发人员造成一定的困扰。
正如 小马 所言,如果已经在使用某些框架,需要具体问题具体分析。比如上述的条件判断代码,使用 YUI 编码就可以使用
YAHOO.util.Dom.hasClass(el, className)
显得更加的精简,并且相比上述的代码更容易理解。