Javascript hedge condition judgment

Source: Internet
Author: User

Consider the following code

If (node. nextSibling. className = ...){
...
}
If node or node. nextSibling is null, an error is returned ). Therefore, the common solution code is

If (node) & (next = node. nextSibling )&&...){
...
}
Then, when multiple conditions are judged, the code will form the following situation:

If (
(Node )&&
(Node. nextSibling )&&
(Node. nextSibling. className = ...)
...){
...
}
With the increasing judgment conditions, the code will become very ugly ".

There is a small "trick" to 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 in this way

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

Personally, the above code is very streamlined from a certain perspective. However, in the actual coding process, especially when many people work together, these codes may cause some troubles to other developers.

As Pony said, If you are already using some frameworks, You need to analyze specific issues. For example, the above condition judgment code can be used using YUI encoding.

YAHOO. util. Dom. hasClass (el, className)
It is more streamlined and easier to understand than the above Code.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.