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

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 篱式条件判断


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 331 ::
收藏到网摘: 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)
显得更加的精简,并且相比上述的代码更容易理解。