Javascriptif condition judgment method summary _ javascript skills

Source: Internet
Author: User
Today, when adding some code functions to the website, we need to use the if condition judgment, and we find that the shorthand method is forgotten. Here we specially sort out the condition statements to execute different actions based on different conditions.

Condition Statement

Generally, when writing code, you always need to perform different actions for different decisions. You can use conditional statements in the code to complete the task.

In JavaScript, we can use the following conditional statements:

• If statement-this statement is used only when the specified condition is true.
• If... else statement-code is executed when the condition is true, and other code is executed when the condition is false
• If... else statement-use this statement to select one of multiple code blocks for execution
• Switch statement-use this statement to select one of multiple code blocks for execution

If statement

The code is executed only when the specified condition is true.

Syntax

The Code is as follows:


If (condition)
{
Only code executed when the condition is true
}

Note: Use lower case if. Using uppercase letters (IF) will generate JavaScript errors!

Instance
When the time is less than, a "Good day" greeting is generated:

The Code is as follows:


If (time <20)
{
X = "Good day ";
}

The result of x is:

Good day

Try it yourself

Note that in this syntax, there is no... else... You have told the browser that the code is executed only when the specified condition is true.
If... else statement
Use the if... else statement to execute code when the condition is true and other code when the condition is false.

Syntax

The Code is as follows:


If (condition)
{
Code executed when the condition is true
}
Else
{
Code executed when the condition is not true
}

Instance
When the time is less than, you will receive a greeting "Good day"; otherwise, you will receive a greeting "Good evening ".

The Code is as follows:


If (time <20)
{
X = "Good day ";
}
Else
{
X = "Good evening ";
}

The result of x is:

Good day

Try it yourself
If... else if... else statement
Use the if... else statement to select one of multiple code blocks for execution.

Syntax

The Code is as follows:


If (condition 1)
{
Code executed when condition 1 is true
}
Else if (condition 2)
{
Code executed when condition 2 is true
}
Else
{
Code executed when neither condition 1 nor condition 2 is true
}


Instance
If the time is less than, the greeting "Good morning" will be sent; otherwise, if the time is less than, the greeting "Good day" will be sent; otherwise, the greeting "Good evening" will be sent ":

The Code is as follows:


If (time <10)
{
X = "Good morning ";
}
Else if (time <20)
{
X = "Good day ";
}
Else
{
X = "Good evening ";
}

The result of x is:

Good morning

In javascript, what values can be used as conditions for if?

1. boolean variable true/false
2. The number is not 0, not NaN/(0 or NaN)

As shown in the following example, if the statement is false instead of negative values.

The Code is as follows:


Var I =-1;
If (I ){
Alert ('where ');
} Else {
Alert ('test is OK! ');
}

3. The object is not null/(null or undefined)
4. Non-empty string ("")/empty string ("")

To sum up, for strings, there is no need to write a lot of if (str! = Null & str! = Undefined & str! = ''), Just use one sentence

The Code is as follows:


If (! Str ){
// Do something
}

You can.

For the non-null judgment of numbers, consider using the isNaN () function. NaN is not equal to any type of data, including itself, and can only be judged by isNaN. For numeric type, if (a) is false when a is 0 in if (a) statement, if (a) is true if (a) if not 0

The Code is as follows:


Var B;
Var a = 0;
A = a + B;
If (){
Alert ('1 ');
} Else {
Alert ('2 ');
}
If (isNaN ()){
Alert ('a is NaN ');
}

Javascript Tutorial: simplified if statement Optimization Method

UglifyJS is a tool for compressing and beautifying javascript. In its documentation, I see several methods for optimizing if statements. Although I haven't used it for some trial tests, I can see from here that it has done some beautification work on js. Some people may think that the if statement is so simple and can be optimized to what extent? But if you look at the following methods, you may change your mind.

I. Use common ternary Operators

If (foo) bar (); else baz () ;=> foo? Bar (): baz ();
If (! Foo) bar (); else baz () ;=> foo? Baz (): bar ();
If (foo) return bar (); else return baz () ;=> return foo? Bar (): baz ();

You are certainly not familiar with the above use of the ternary operator to optimize the if statement. Maybe you often use it.

Example provided by the home of scripts:

The Code is as follows:


Script
Var I = 9
Var ii = (I> 8 )? 100:9;
Alert (ii );
Script

Output result:

100

2. Use the and (&) and or (|) Operators

If (foo) bar () ;=> foo & bar ();
If (! Foo) bar () ;=> foo | bar ();

Honestly, I didn't write code like this. I saw it when I learned "laruence's Linux house dish", but I didn't expect to implement it in js.

3. Omit braces {}

If (foo) return bar (); else something () ;=>{ if (foo) return bar (); something ()}

You are familiar with this writing method, but I suggest you do it during code optimization or hand it over to UglifyJS to help you solve it. After all, there is one less braces, and the code is not highly readable.

Here, I think of a method for getting HTML element attributes in "proficient JavaScript" by the father of jQuery.

Function getAttr (el, attrName ){
Var attr = {'for': 'htmlfor ', 'class': 'classname'} [attrName] | attrName;
};

If we do not write this way, we may need to use two if statements for processing. The above code is not only concise and effective, but also highly readable.

Think about it. In some cases, we can find an effective way to solve the problem, but the key is whether we try to find a better way.

[Javascript tips] short for if (x = null)

If (x = null) or if (typeof (x) = 'undefined') can be abbreviated as if (! X), not verified.

Otherwise, if (x) indicates that x is not null.

Determine whether an object exists

The Code is as follows:


If (document. form1.softura9 ){
// Determine whether softur95. js errors are prevented.
}

The Code is as follows:


If (document. getElementById ("softura9 ")){
// Determine whether softur95. js errors are prevented.
}

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.