JavaScript's branching judgment with built-in objects

Source: Internet
Author: User
Tags floor function local time

One, branching structure
    • Single selection structure (IF)
    • Two-way selection structure (IF/ELSE)
    • Inline ternary operator?:
    • Multi-channel selection structure (switch)
var condition = true; if (condition) {      alert ("I will appear!") ");  }  condition = false; if (condition) {      alert ("I won't appear!") ");  } else {      alert ("I will appear!") ");  }  Condition = "some string"; if (condition) {      alert ("can be judged directly on any data type, the calculation will automatically convert it to a Boolean value at judgment time!");  } var val = condition? " When True I will be returned ":" When it is false I will be returned ";  Alert (val);//Outputs "when True I will be returned"

For if: Else statement, you can not use "{}" if you want to execute only one statement, but this is not recommended. But it does do this to simplify the code:

var str= "one"; if (str== "one") alert ("The value of str is string ' one '"; else alter ("not one"))

Although there is no if .... ElseIf structure in JavaScript, you can use the If...else shorthand method to get

 To determine the range of results entered by the user, we used multiple nested IF.    else statement var num = window.prompt ("Please enter XXX's score!", ""); The num *=1;//window.prompt method always returns only a string, in such a way that it is converted to a number if (IsNaN (num) && num) {//cannot convert other values to a number when Nan is returned,    You can use the built-in isNaN to determine if the value is Nan alert ("You are not entering a number!");        } else {if (num<=100 && num>=90) {alert ("excellent!");            } else {if (num =80) {alert ("good!");                } else {if (num < && num >=) {alert ("so So!");                    } else {if (num < && num >=60) {alert ("Be careful!!!");                        } else {if (num < && num >= 0) {alert ("Oh, no!");                        } else {alert ("usb!"); }}}}}}//The above code because of the use of multiple if. Else nesting, it is very confusing, simplification only need to take the else after the curly braces off the line//if (...) {...} This is an if (IsNaN (num)) {alert ("You are not entering a number! ");}    else if (num<=100 && num>=90) {alert ("excellent!");    } else if (num =80) {alert ("good!");    } else if (num < && num >=) {alert ("so So!");    } else if (num < && num >=60) {alert ("Be careful!!!");    } else if (num < && num >= 0) {alert ("Oh, no!");    } else {alert ("usb!"); }//looks much clearer, but note that there is no elseif in JavaScript, so there are spaces between the else if

Switch statement for multiple judgments

Switch (condition) {//switch is the meaning of the jump (also known as "switch"), so the switch statement is to judge the situation, jump to the situation to begin execution case        4:            alert ("C value is 4"); Cases 3:            alert ("Value of C must be greater than or equal to 3"), Case 2:            alert ("Value of C must be greater than or equal to 2"), Case 1:            alert ("C's value must be greater than or equal to 1");    }//Can be used Break to only execute a statement that conforms to one condition,    switch (condition) {Case 4:            alert ("Value of C is 4"), Break, Case 3:            alert ("Value of C is 3"), break, Case 2 :            alert ("Value of C is 2"), break, Case 1:            alert ("Value of C is 1"), break;    } var condition= "one"; switch (condition) {// Switch can not only judge the number, but also can judge the string, even the variable case        "one":            alert ("Condition value is the string ' one '!"); break; case "three":            alert ("condition value is String ' three '"), break, Case "four":            alert ("The value of condition is string ' four '!"), break, case "five" :            alert ("condition value is String ' five '!"); default://when all conditions do not match, the alert after the default statement is executed            ("We must be foolproof!"). condition is nothing! ");

  

Second, the cycle

Loops are used to indicate which actions to repeat when certain conditions remain true. When the condition is met, it jumps out of the loop statement. There are four loop structures available in JavaScript.

    • Loop controlled by counter (for)
    • Test expression at the beginning of the loop (while)
    • Test expression at the end of the loop (Do/while)
    • operate on each property of an object (for/in)

The For statement specifies a counter variable, a test condition, and an action to update the counter. The condition is tested before each iteration of the loop. If the test succeeds, the code in the loop is run. If the test is unsuccessful and does not run the code in the loop, the program continues to run the first line of code immediately following the loop. After the loop is executed, the computer variable is updated before the next loop.

The for (Var i=0;i<10;i++) {//for loop has three sentences in parentheses,    //1 for each. Initial make counter 2. Determine the condition Update counter        alert ("I current value is" +i);    }

In fact, the FOR Loop statement can write exactly this, the following code and the above effect is the same (although not necessary, but from such a code can clearly see how the For loop works)

The Var i=0;//loop is initialized before initializing I for    (;;) {The//for statement must have three statements in parentheses, but it can be an empty statement        if (i<10) {//when the condition is true, the code alert is executed            ("I Current value is" +i);        } else {//exits the loop when the condition is false)            break;//use break to exit the loop}    }

A dead loop is the best way to describe while working (but we can never do it in real programming)

while (true) {        alert ("You can't shut me out!") ");//This is what the so-called Master wrote on the Internet" closed window (Zhou new song, recommend) "Code    }

Do.. The while loop differs from the while loop in that it executes at least one of the code in the code block once

Do {        alert ("I'm sure to appear once");    } while (false);

  

Third, common built-in objects

The so-called built-in object is ECMAScript provides some of the objects, we know that the object has the corresponding properties and methods, in fact, many of the JS object here is similar to many of the Python syntax

3.1 Arrays Array

1. How arrays are created

    • The literal way to create (recommend that you use this way, simple rough)
var colors = [' red ', ' color ', ' yellow '];

  

    • Create an object using the New keyword to create the constructor using the constructor (which is spoken later)
var colors2 = new Array ();

  

2, assigning values to arrays

var arr = [];//one by one assignment by subscript arr[0] = 123;arr[1] = ' hahaha '; arr[2] = ' hehe hey '

  

3 Common methods of arrays

Method Description
Concat () Combine several arrays into an array
Join () Returns a string that contains all the elements in an array that are concatenated together, separated by the specified separator
Pop () Move the last element of the divisor group
Shift () Move the first element of an divisor group
Unshift () Adds an element to the beginning of the array and returns the new length
Slice (start,end) Returns a segment of an array
Push () Adds an element to the end of the array and returns the new length
Sort () Sorting an array
Reverse () Invert an array
Length It is an attribute, the only one that gets the length of the array, which can be combined with a for loop traversal operation
3.2 Strings String
Method Description
CharAt () Character that returns the position of the specified index
Concat () Returns a String value that represents the concatenation of two or more strings
Match () Returns a regular expression pattern to produce a string and returns the containing lookup result as a result (the following regular expression course will be detailed)
Replace (A, B) String B replaces the A
Search (Stringobject) Well-known whether there is a corresponding match. If a match is found, the search method returns an integer value indicating the offset from the beginning of the match distance string. If no match is found, return-1
Slice (start,end) Returns the string between start and end-1, starting at 0
Split (' A ', 1) String split, split with a, the first parameter returns the maximum length of the array
SUBSTR (Start,end) String intercept, left close right open
toUpperCase () Returns a new string that becomes uppercase
toLowerCase () Returns a new string that has been converted to lowercase
1. Convert number type to string type var num = 132.32522;var numstr = num.tostring () console.log (typeof Numstr)

  

Rounding var newnum = num.tofixed (2) console.log (Newnum)

  

3.3 Date Object

Create Date object only constructor one way, use the New keyword

Created a Date object var mydate = new Date ();

  Common methods

Grammar meaning
GetDate () Returns the day ordinal (1-31) of the month of the specified date object based on local time.
Date () Returns the date and time of day based on local time
GetMonth () Returns the month of the specified date object based on local time (0-11)
getFullYear () Returns the year of the specified date object based on local time (four digits are returned in four-digit years)
GetDay () Returns the day ordinal of the week of the specified date object based on local time (0-6)
GetHours () Returns the hour of the specified Date object based on local time (0-23)
Getminutes () Returns the minute of the specified Date object based on local time (0-59)
Getseconds () Returns the number of seconds of the specified Date object based on local time (0-59)
3.4 Math built-in objects

Common built-in objects

Method meaning
Math.floor () Rounding down, called "floor function"
Math.ceil () Rounding up, called ' floor function '
Math.max (A, B) Find the maximum value in a and B
Math.min (A, B) Find the minimum value in a and B
Math.random () Random number, default 0-1 random number, Formula Min+math.random () * (max-min), to find the number between Min~max

JavaScript's branching judgment with built-in objects

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.