Javascript 篱式条件判断
发布日期:2021-09-08 22:55:14 浏览次数:20 分类:技术文章

本文共 624 字,大约阅读时间需要 2 分钟。

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 == ...) {
...

转载于:https://www.cnblogs.com/gaho213/p/7499916.html

转载地址:https://blog.csdn.net/weixin_34341229/article/details/93407838 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:SGU 144.Meeting
下一篇:LeetCode | Regular Expression Matching

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2024年04月01日 03时46分23秒