Home  >  Article  >  Web Front-end  >  Javascript fence condition judgment_javascript skills

Javascript fence condition judgment_javascript skills

WBOY
WBOYOriginal
2016-05-16 19:01:541158browse

Consider the following code

if (node.nextSibling.className == ...) {
...
}
in case node or node.nextSibling is null , an error will be returned. So, usually the solution code is

if ((node) && (next = node.nextSibling) && ... ) {
...
}
Then , when the condition is judged to be one or more, the code will form the following situation

if (
(node) &&
(node.nextSibling) &&
(node.nextSibling.className = = ...)
... ) {
...
}
As the number of judgment conditions continues to increase, the code will become very "ugly".

There is a small "trick" that can simplify the conditional judgment expression. We can add an empty object ({}) or zero (0) as an alternative

if ( next = (node ​​|| 0).nextSibling) ) {
...
}
Then, the above code can be written like this

if (((node ​​|| 0).nextSibling || 0).className == ...) {
...
}
--Split--

Personally, the above code will be very streamlined from a certain perspective. However, in the actual daily coding process, especially when multiple people cooperate, these codes may cause certain troubles to other developers.

As Xiao Ma said, if you are already using certain frameworks, specific issues need to be analyzed in detail. For example, the above conditional judgment code can be used using YUI coding.

YAHOO.util.Dom.hasClass(el, className)
appears to be more streamlined and easier to understand than the above code.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn