Javascript Hedges to judge _javascript skills

Source: Internet
Author: User
Consider the following code

if (Node.nextSibling.className = = ...) {
...
}
If node or node.nextsibling is null (NULL), an error is returned. So, typically, the code for the solution is

if (node) && (next = node.nextsibling) && ...) {
...
}
Then, when the condition is judged by more than one case, the code will form the following situation

if (
(node) &&
(node.nextsibling) &&
(Node.nextSibling.className = = ...)
... ) {
...
}
With the constant increase in judgment conditions, the code becomes very "ugly".

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

if (Next = (node | | 0). nextSibling)) {
...
}
So the code above can be written like this

if ((node | | 0). nextSibling | | 0). ClassName = = ...) {
...
}
--split--

Personally, the code is very streamlined in some ways. But in the day-to-day coding process, especially with the cooperation of many people, this code may cause some trouble to other developers.

As Xiao Ma says, if certain frameworks are already in use, specific problems need to be analyzed. For example, the above conditions to judge the code, using the YUI code can be used

YAHOO.util.Dom.hasClass (el, ClassName)
is more streamlined and easier to understand than the code above.

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.