JavaScript Base Statement

Source: Internet
Author: User
Tags bitwise operators logical operators

First, preface:

Having experience of learning other languages will be better to get started. But it's nothing to learn. As long as you study hard, you will learn well. After all, it's just some basic statement. The key is to use it. Mastering the nesting of good sentences, and the logical thinking ability, has successfully more than half.

Second, JS variables and input and output

Three ways to use JS

1. Embedded JS directly in HTML tags (not advocated) is not in line with the requirements of the separation of content and behavior!!!!
          

<button onclick= "alert (' Hurry up, o ' ah ')" > O </button>

     
2. In the HTML page, use the <script></script> tag package code;

<script type= "Text/javascript" >//JS code </script>

<script></script> tags can be placed in any position on the page can also be put more than one, but generally only a

3. Introduction of external JS files
<script language= "JScript" src= "js file path" ></script>
Precautions
1. <script></script> can be embedded in any location of the page, but the different positions will cause the JS code to execute in different order
For example <script></script> put in <body></body> before the JS code will be executed before the page is loaded
2. The introduction of external JS code,<script></script> must be paired with the appearance of the label. And there's no more code in the tag.

The variables in JS
The wording of variable declarations in 1.JS
var num = 10;//variables declared with VAR belong to local variables and are valid only within the current scope.
However, if you declare it directly in <script>, it is equivalent to a global variable

num = 10;//A variable declared with VAR, which defaults to a global variable, is valid throughout the JS file (below the statement).

var x=8,y, z = 10; Declare multiple variables at the same time using a single line statement. In, Y is declared, but not assigned, and the result is undefined

Considerations for declaring variables
In ①.js, all variables are declared using the var keyword. The specific type of variable depends on the type of value assigned to the variable;
②.js, the same variable, you can change the data type of the variable at multiple different assignments;
var a = 10;//from the initial declaration, a is an integer type
A = "hahaha";//re-assignment, the integer type A is modified to the string type;
③. Variables are either declared with Var or not with Var;
The "difference" using the Var declaration is a local variable, not a global variable with VAR

④. Only declare with VAR but not assign value. The result is undefined.
For example: Var a;//only declares a that is not assigned a value of undefined. However, if you do not declare or assign a value of a, direct use will give an error.

⑤. The same variable name, you can use the Var declaration multiple times, but the latter var does not have any effect. The second time the Var declaration is used, it is only understood as a normal assignment operation

2. Naming requirements for variable names
①. Variable names can only have, letters, numbers, underline composition;
②. The beginning cannot be a number;
③. Variable names are case-sensitive. Uppercase and lowercase letters general declaration constants for different variable capitals

3. Naming conventions for variable names
①. To conform to the small hump rule (Camel name law):
The first letter is lowercase and the first letter of each word is capitalized; for example: mynameispengwei√
②. Or use the Hungarian nomenclature:
Said to have the letter lowercase, between the words separated by _ my_name_is_peng_wei√
③.mynameispengwei can be used, but not standardized

Data types in 4.js: are declared with Var, but what type of variable is, depending on the type of value assigned to the variable;
ndefined: Not defined. Variables declared with VAR have been used, but no value has been assigned. var A;
Null: Represents an empty reference.
Boolean: Boolean type. means true or false. Only two values: True/flase
Number: Numeric type. Can be an integer, or it can be a decimal.
String: Type. The content enclosed in double or single quotation marks is called a string.
Object: Type. Follow-up explanation ....

5. Common numeric functions
①isnan (): Determines whether a variable or constant is Nan (not a number value)
Nan is not equal to Nan
When judged using isNaN (), an attempt is made to convert using the number () function, which is not nan if it is eventually able to be converted, and the result is flase

②number () function: Attempts to convert other types of data to numeric;
"String Type"
"String is a pure numeric string and will be converted to the corresponding number:" One "-->11
String is an empty string and will be converted to 0; "" -->0
string contains any other characters, it cannot be turned; "1a"-->nan
"Boolean type"
True->1 flase->0
"Null and undefined type"
Null->0undefined->nan
"Object"
* (Follow-up explanation)
③parseint (): Converting a string to an integer type
"Empty string, cannot go." ""-->nan
A string containing other characters will intercept the number part before the first non-numeric string
"12a23"-"Aqw12"-->nan
"parseint () can only be converted to strings and integers (can be converted to integer), to other types, all Nan

☆ "number function differs from parseint function" focus
1.number function can go to various data types, parseint function can only go to string
2. The results are not exactly the same when you turn the strings (see above for explanations)

④parsefloat: Converting a string to a numeric type
The conversion rule is the same as parseint, except that if there are decimals, the decimal point is preserved, and if there are no decimals, it remains an integer;
"12.5"-->12.5 "-->12"
⑤typeof: The data type of the monitoring variable:
String-->string numeric-->number undefined-->undefined
True/flase-->boolean Object/noll-->object function-->function

"Input and output statements commonly used in JS"
1.document.write (). Print the contents of () to the browser screen
When you use it, be aware that everything except the variable constants must be placed in the. Content outside of variables and constants must be placed outside the ""
If you have variables and strings at the same time, you must use the + link eg:document. Write ("Solitaire in the left hand" +left+ "<br/>");
2.alert (): Use pop-up window output
Pop-up Warning, () the content is the same as the above requirements
3.prompt (): Pop-up window input;
Accept two-part parameters
① the contents of the input box above, optional
② The default information in the input box, optional
Indicates the contents of the input box when only part is written;
You can define variables to accept the input content. Click on the OK button, the variable will be assigned to the input content, click the Cancel button, the variable will be assigned a value of NULL
When you enter content, the data type that is accepted by default is a string!!

Third, operator

1. Arithmetic operations (single-mesh operator)
+ Plus,  -minus,    *,    /,    %,    ++ auto-increment,   ; --Auto-subtract

Note: when there are addition and subtraction operations, be aware of whether you want to convert numbers to numeric values

① +    : There are two functions: link string and addition operation .
When the + sides are all numbers, the addition operation;
when a string is used on either side of the link string, the result of the link is the string
except +, and the rest of the symbol operation will attempt to convert the function variables to the number ② /   :   results will be reserved for decimal point
③  + +  : self-increment operator, the variable is based on original +1
④   -- : self-decrement operation           1


1. Same: Either a++ or a--, the value after the operation is added 1;
2. XOR: a++, first use the value of a to calculate, and then add a plus 1
 ++a, first put a+1, and then use the value after a+1 to calculate.
For example

 var  a = 3,b,c;b  = a++ + 2; //         first with a operation: b = 3 + 2, then a+1:a = 4  c = ++a + 2; //     now a+1:a = 5; Then use a value operation: c = 5 + 2;  // a=5 b=5 c=7  


2. Assignment operation
= Assignment = = = *=/=%=

+ =: a+=b: Equivalent to A=a+b, but the former is more efficient than the latter, so the person who pushes the pre-recommendation

3. Relational operations
= = equals, = = = strictly equals = = Not equal to,!== not congruent >, <, >=, <=

① relational operator, the result after operation, can only be a Boolean type;
② determine if a number is in a certain range, it must be connected with &&
Eg:a<10 && a >0√10>a>0x

③===: Strictly equals: Requires not only the same type, values must be the same, different types, the result is directly false, the same type, and then the next judgment
= = equals: The same type as the = = = effect. Type is not the same, the first attempt is to use the number function to convert both sides to numbers before judging
However, there are individual exceptions
Alert (Null = = = Flase) result is false


var A;
Alert (A = = NULL) result is true

Alert (nan = = Nan) result is false

Alert (1!= "1") result is false
Alert (1!== "1") result is true

4. Conditional operator (multi-mesh operation)
A>b?true:false
There are two important symbols:? And:
When? The preceding section, when the result of the operation is true, executes: the preceding code
When? The preceding section, when the result of the operation is false, executes: The following code

A value can be used on either side of the colon, and the entire formula can be assigned. var a = 1 > 2? 1:2;
Both sides of the colon can be code blocks, and code is executed directly. 1 < 2? Alert (1:alert (1);
Multi-mesh operators can be nested in multiple layers. var a = 1< 2? Alert (1): alert (1);


5. Bitwise operators, logical operators
&& and, | | Or! Non (single-mesh operator)

&&amp: The result is true when both sides are established
|| : The result is true when either side is set

6. Precedence of Operators
() parentheses Highest
! ++ --
*     / %
+    -
> < >= <=
==   !=
&& | | ,&& priority is higher than when && exists at the same time | |
||
= + = = *=/= The lowest value of the assignment

Four. Branching structure

  1. Multi-mesh operator
A>b?true:false

2. If-else structure
The wording of ① structure
if (judging condition) {
When the condition is true, execute if {}
}else{
When the condition is false, execute else's {}
}

②. Precautions
The ①ELSE statement block. can be omitted according to the situation.
{} After ②if and else can be omitted, but {} is omitted, if and else are followed by only one statement, so it is not recommended to omit {}.
③if () in the condition of the judgment, supported by:

①boolean:true is true, Flase is false;
②string: Non-empty string is true, empty string is false;
③number: not 0 digits are true, 0 is false;
④null/undefined/nan: All is false;
⑤object: All is true.

3. Multiple if, step if structure
①. Structure notation
if (condition 1) {
When condition 1 is established, the support statement
}else if (condition 2) {
Condition 1 is not established, and when condition 2 is established, the statement executed
}else{
When all of the above conditions are not true, the executed statement
}
    
②. In multiple if structures, each judgment condition is mutually exclusive, and execution chooses one of the paths to execute. After encountering the correct options and executing, jump out of the structure, not judging the subsequent branch


4. Nested IF structure
① structure notation
if (condition 1) {
Condition 1, established

if (condition 2) {
Condition 1, and Condition 2, established
}else{
Condition 1 established, Condition 2 not established
}
}else{
Condition 1, not established
}

②. In a nested if structure, if you omit {}, the else struct will always belong to the if structure closest to it
③ nested structures can be nested multiple times, but generally do not recommend more than three layers
It is generally not recommended to use nested if when using multiple if structures.

5.switch-case structure
①. Structure notation: The following
② Precautions:
①switch the expression in the Organization (), you can use the various data types supported by JS.
The ②switch mechanism uses the = = = judgment when making judgments.
The expression following the ③case (which allows multiple statements) can be a variety of data types, but the value requirements for case are different, otherwise, they will only be executed, the first case
④break function: After executing the case code, jump out of the current switch mechanism
Missing break Consequences:
Execute all subsequent case and default starting from the first correct case item;
Reason: When a switch structure is judged, it will only judge the correct answer, and when the correct case is encountered, it will no longer judge the subsequent project
The ⑤switch structure performs more efficiently than multiple if. In a multi-channel branch, it is recommended to use switch

Five. Cyclic structure

Steps to perform the 1.WHILE loop structure
①. Declaring a loop variable
② Judging Cycle conditions
③. Performing a loop body operation
④ Updating loop variables
Then, the loop executes a few, until the condition is not set, jumping out of the loop.

The expression in the while loop structure () can be of various types. But in the end it turns out to be true, and the conversion rules are the same if structure.

    var num = 0;                                                  // declaring a loop variable     while (Num < 10) {                                          // Judging the cyclic condition            document.write (num + "<br/>");           // performing cyclic gymnastics                num=num+1;                                     // Update loop variable    }                            

2.do-while Cycle Structure
Do-while Cycle Characteristics: First judge, then execute.
Do-while cycle characteristics: First execution, then judgment. Even if the initial conditions are not true, the do-while cycle is cycled at least once.

    var num = ten;      Do {    document.write (num); /    num--;    }  while (num >= 0);

3.FOR Cycle Structure

1. For loop has three expressions: ① declares the loop variable; ② determines the loop condition; ③ updates the loop variable
Between three expressions, separated by a semicolon
The three expressions for the For loop can be omitted, but the two semicolons are integral

2. For loop execution characteristics: First judge, then execute; same as while.

3. For loop three expressions, can have a multi-part, the second part of a number of judging conditions in the && | | Connection, first, three parts are connected by commas.

"Loop control Statement"
1. Break: Jump out of this layer loop and continue with the statement following the loop.
If the loop has multiple layers of nesting, then break can only jump out of one layer

2. Continue: Skip the remaining code in this loop and proceed to the next loop.
① for A For loop, continue executes after the statement, when the loop variable UPDATE statement i++;
② for While,do-while Loops, the statement executed after continue is a cyclic condition judgment,
Therefore, when these two loops are used, continue must be placed after the i++ is used. Otherwise, continue will skip i++, leading to a dead loop.


       for (var num = 1, num1=;  Num <=  9 && num1  >=   ; num++, num1--) {        + "<br/>");    }

Six. Functions

1. Declaration and invocation of functions
①. declaration format for Functions
            

function function name (parameter 1, parameter 2, ...) {    // function Body Code return      value;}        


The invocation of the ② function:
① call directly: the function name (the value of parameter 1, the value of parameter 2, ...). );
② Event Invocation: In an HTML tag, use the event name = "Function name (the value of parameter 1, the value of parameter 2, ...). )"

<button onclick= "saysth (' blue ', ' haha-ha ')" > click, Print </button>


2. Considerations for Functions

The ① function name must conform to the small hump rule: The first letter is lowercase, and then the first letter of each word is capitalized

The parentheses after the ② function name can have parameters or no arguments, respectively called the parameter function, and no argument function.

③ the argument list when declaring a function is called a formal parameter list. (The name of the variable)
function Saysth (color,str) {}
A list of arguments when the function is called, called the argument list. Actual parameters (assigned values of variables)
Saysth ("Red", "Change a Shadow");

The number of formal parameter lists for the ④ function does not actually relate to the number of argument lists.
The number of function arguments, depending on the argument list.
If the number of argument lists is less than the formal parameter list, the non-assigned parameter will be undefined

The ⑤ function can have a return value and return the result using return.
When calling a function, you can use a variable to accept the return result of the function.
If the function does not return a value, the accepted result is undefined.

function Fun () {return "Hahah";} var num = Fun ();    // num = hahah    


Scope of variables in the ⑥ function:
Only functions in JS are scoped: function scope.
That is, local variables in the function {} can only be used in function fields. Other local variables in {} (such as: for{}) can be used outside of {}.
function, the variable declared with VAR is a local variable and can only be accessed inside the function;
Variables declared without var are global variables and can be accessed outside of the function.
The parameter list of a function, which defaults to a local variable, can only be used inside a function.

The declaration of the ⑦ function has no precedence over the invocation of the function, that is, the function can be called before the function declaration

Fun ();    // called before the fun Declaration can also be function Fun () {return "Hahah";}


seven. Declaration and use of anonymous functions

1. Declares an anonymous function to assign a value directly to an event
Window.onload = Functio N () {}

2. Use an anonymous function expression to assign an anonymous function to a variable.
Declaration: Var func =function () {}
Call: Func ();

Note: When using an anonymous function expression, the function's invocation statement must be placed after the function declaration statement!!! (The difference from the normal function!!!)    )

3. Self-executing function:
①!function () {} (); You can start with a variety of operators, but generally!
!  function (formal parameter list) {} (argument list);

② (function () {} ());  Wrap

③ (F unction () {}) with the parentheses after the function and function (); Use () Only wrap function section

Three kinds of characters:
① use! The beginning, the structure is clear, is not easy to confuse, the recommendation uses;
② can indicate that anonymous functions and calls are a whole, officially recommended;
③ cannot indicate the integrity of functions and subsequent (), and is deprecated.

4. Internal properties of the function
1. Arguments Object
① effect: Used to store all arguments when the function was called. When we call a function and assign a value with an argument, the argument list is actually saved to the arguments array, and
can be called in the function, using arguments[n]. N starting from 0. The number of
②argument arrays, depending on the argument list, is independent of the parameter.
However, once the nth position of the formal parameter, the argument, arguments are present, the shape arguments in the arguments binding, the synchronization changes.
     (that is, the value of the parameter is modified in the function, arguments also changes.) Conversely, it is also established)

③arguments.callee () is the primary property of arguments. Represents the reference address of the function where the arguments is located;
inside the function, you can call the function itself using Arguments.callee (). Within a function, the
calls the function itself, called recursion.
structurally similar to do-while structure

var num = 1; function func () {            // recursive    console.log (num);            // Do , loop at    the beginning num++;                        // Cyclic gymnastics for    if (num<=4) {                   //while, judging condition        Arguments.callee ();        // handed     }        num--;                            // return     console.log (num);} Func ();        

Code Execution Order:




Recursion is divided into two parts: recursion and attribution. The function can be divided into the upper and lower parts by using recursive call statements as bounds.
Recursive: When the function executes the upper part and encounters its own invocation statement, it proceeds to the inner function and executes the upper part. Until the most inner function is executed.
Return: When the inner function is finished, the bottom half of the function is gradually executed starting from the inner function.

When the outermost function executes, it encounters its own invocation statement, which goes into the inner function execution, while the second part of the outer function is temporarily not executed.

Until the most inner function finishes executing, it is gradually outward executed.

Console.log (history);

JavaScript Base Statement

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.