JS Basics and Loops

Source: Internet
Author: User
Tags true true

JS Introduction

[Three ways of JS]
1. Embedded JS in HTML tags
<button onclick= "Javascript:alert (' idiot ')" > Ha ha </button>

2, the HTML page directly using JS
<script type= "Text/javascript" >
JS Code
</script>

3. Referencing external JS file
<script language= "javascript" src= "JS file path" ></script>


[Precautions]
① page JS code and Reference JS code, you can mosaic to any location of the HTML page. But the different location will affect the execution order of JS code;
For example,:<script> in front of the body, will execute the JS code before the page loads
② page JS code, using type= "Text/javascript"
Referencing external JS files using language= "JavaScript"
③ Reference External JS code <script></script> tags, must appear in pairs, and the tag can not have any code!

the variables in JS
1, the wording of the variable declaration in JS
VAR width=10;//variables declared with Var, only valid at the current function scope.
width=12;//does not use Var to directly assign the generated variables. The default is the family variable, the entire JS file is valid
var a,b,c=1;//the same declaration statement declares multiple variables at the same time, separating the variables with commas. But the assignment needs to be assigned separately,
For example, only c=1,a/b in the above formula is undefined [underfined]

[Declaration of variable considerations]
All variable type declarations in ①js use the var keyword. The specific data type of the variable, depending on the type of assignment to the variable
② the same variable can modify the data type of a variable at multiple different assignments:
var width=10;//width as shaping variable
width= "haha";//width is changed to string type
The ③ variable can use VAR, or you can omit var. [difference] does not use VAR, the default is the global variable
④ the same variable name, you can declare multiple var. But there is no meaning and no error. The declaration after the second time will only be interpreted as an assignment;

2. Naming conventions for variables
① variable names can only be composed of letters/numbers/underscores/$
② cannot start with a number
③ variables are case-sensitive, uppercase and lowercase letters are different variables

3, the name of variable names to comply with the camel rule:
The variable starts with lowercase, and then the first letter of each word is capitalized
Or split with an underscore

4, the data type of the variable in JS
undifined: Undefined, variable declared with VAR, no initialization assignment. var A;
Null: Represents a special variable type. The unique value is NULL, which indicates null. var a = null;
Boolean: True or FALSE, optional value True/false
Number: Numeric type. Can be a decimal, or an integer.
String: Type. Use "" or "wrapped content to become a string.
Object (complex data type): Subsequent explanations, functions, arrays, etc...

5, the commonly used numerical functions:
①isnan: Used to determine whether a variable or a constant light is a Nan (non-numeric)
When you use isNaN to determine, you try to convert using the number () function, and if you can convert to numbers, it is not a non-numeric result of false
"111" Pure numeric string, false "" "empty string, false" 1a "contains other characters, true
True/false Boolean type, False
②number (): Convert other types to numeric types
[String type to value]
>>> string is a pure numeric string and will be converted to the corresponding number "111"->111
>>> when the string is an empty string, it is converted to 0 ""->0
>>> cannot convert "111a" when string contains other non-string->nan

[Boolean Boolean type to numeric value]
True->1 false->0

[null/undefined to value]
Null->0 Undefined->nan

[Object type to value]
Call the valueof function first to determine if the function has a return value, and then judge it according to the various conditions described above.

③parsint: Converting a string to a numeric type
>>> empty string, cannot go. Result is Nan
>>> Pure numeric string, can go. "123"->123 "123.5"->123 (decimal conversion, directly erase the decimal point, not rounding)
>>> A string containing other characters that will intercept the numeric part before the first non-numeric character.
"123a45"->123 "A123b45"->nan
>>>parsint can only be converted to string type, boolean/null/undifined are Nan

④parsefloat: Converting a string to a numeric value
>>> use the same method as ③. But the decimal point is preserved when converting decimals
"123.5"->123.5

⑤typeof: Used to detect data types
->undifined string->string not defined True/false->boolean
Numeric->number object/null->object function->function

[Input/output statements in JS]
1, printed in the document input: document.write ();
Output statement that will write the contents of the () on the browser screen:

Note: Any content that is unexpected to the variable/constant must be placed in "" while printing, and the variable/constant must be placed outside the "".
When the printed content is composed of multiple parts, a + link is used between them:
For example: document.write ("Solitaire in the left hand:" +left+ "<br/>");

2. Pop-up window output: alert ();
The use of the pop-up Warning, (), ibid.

3, pop-up window input prompt ("Please enter your name:", "XX");
Two-part parameter: ① The message above the input box
② The default information in the input box
The two are separated by commas, and only part of the message is indicated by default;
The default received data is a string

Variables can be defined to receive input, such as Var name=prompt ("Please enter your name:", "XX");
Click the Confirm button, enter the change click Cancel button, Name=null

JS operator

[arithmetic "
" + Plus ""-minus "" * multiply ""/""% "" + + + ""-Self-subtract "
+: There are two functions, the link string/addition operation;
① The addition operation when the + both sides are numbers;
② a string when the string is linked on either side of the + side, and the linked demerit is considered a string.
+ +: The increment operator, the variable on the original basis +1;
--: The self-decrement operator, the variable on the original basis-1;
"n++ and ++n"
n++: First use the value of N to calculate, then n+1;
++n: first n value + 1, then use n+1 after the value, operation;
Same point: Regardless of n++ or ++n, after executing the code, the n+1 will be put.


[assignment operation "
" = Assignment "" + = "" = "" *= ""/= ""%= "
+=:a+=5; equivalent to A=a+5; the former is more efficient than the latter."

[relational operation]
"= = equals" "! = Not equal to "" = = = Strictly equals ">" "<" ">=", "<="
= = = = strictly equals; Type is different return false; Type is the same, and then the next step is judged.
= =: equals; Type is the same, then proceed to the next judgment, the type is different, the number is converted to digital and then judged;
null==undefined[null===undefined[Error]

[conditional operator (multi-mesh)]
A>b?true:false
has two keyword symbols"? And: "
when the previous part of the operation evaluates to True, Execute the preceding code
when the previous section evaluates to False, the following code
can be nested multiple times, for example: Var jieguo=num>5? " Input too big ":(num==5?" It's right! ":" Too small ");

[logical operator]
"&& with" | | or ""! Non-"


[Precedence of operators]
()
! ++ --
% / *
+-
> < >= <=
= =! =
&&
||
various assignments = + = *=/=%=

JS Conditional statement

[If-else structure]
1, the wording:
if (judging condition) {
Execute when condition is true
}else{
Established when the condition is flase
}
2, if () the expression, the result after the operation should be: [Focus]
①boomlean:true true Flase Fake
②string: The non-empty string is true, and the empty string is false.
③number:0 is false; all non-0 are true.
④null/nan/undefined: All is False
⑤object: All is True
3, else{} structure, can be omitted according to the specific circumstances;

[Multiple if/ladder if]
1, the wording:
if (condition i) {
Condition One established
}else if (condition two) {
Condition one is not established, condition two is established
}else if (condition three) {
Condition one does not establish, the condition is not two set up, the condition three establishes
}else if (condition N) {
//......
}

2, multiple if structure, each judgment condition is mutually exclusive! You can only select one bar.

3, If/else best not omit {}
If the {} is omitted, the IF/ELSE structure contains code that is only the most recent line (the semicolon ends);
If you omit {} then the else structure will always enter the nearest if structure in front of it.

[Nested IF]
1. Wording
if (condition i) {
Condition One established
if (condition two) {
Condition I set up && condition II established
}else{
Condition One establishment && condition two not established
}
}else {
Condition one is not tenable
}

2, if structure can be multi-nesting, but in principle, not more than 3 layers

[Switch-case structure]
1, the structure of the wording:
switch (expression) {
case constant expression 1;
Statement 1;
Break
case constant Expression 2;
Statement 2;
Break
....
Default
Statement N;
Break
}
2. Precautions:
The expression of ①switch (), and the expression following each case, can be any data type supported by JS (object and array not);
The constant expression after ②case must be different, otherwise only the first one will be executed;
The constants after ③case can be any data; different case of the same switch structure can be many different data types;
④switch in the judgment of the time, the use of a congruent judgment = = =
⑤break function, after executing the case code, jump out of the current switch structure;
The consequences of missing a break, starting with the right case entry, executing all case and default in turn
The ⑥SWITCH structure will judge the correct answer only once, and when it encounters the correct case, it will no longer judge the subsequent items. Proceed in turn
⑦switch structures are executed faster than multiple if structures. The switch structure is a priority when you have multiple branches.

JS Loop structure

Follow the bad control statement
1.break: Terminate this layer to follow the bad, continue to execute the statement after the bad;
When there are multiple layers in the bad, break will only skip a layer of bad

2.continue: Skip this cycle and continue to do the next bad
For a For loop, continue executes the loop variable UPDATE statement n++ after execution;
For while,do-while,continue execution, continue to perform cyclic condition judgments,
So using two loops is, it must be noted that continue must be used after n++.




[Nesting loop characteristics]
The outer loop controls the number of rows, and the inner loop controls the number of elements per row;

[To do the graphic problem thinking]
1, determine the shape of a few lines, that is, the number of outer loop
2, to determine that each line has several elements, representing a number of inner-layer loops;
3, determine the number of each element, that is, the number of cycles per inner layer;
Tips: Usually, find out the number of each element, the relationship with the line number, which is the maximum value of the current inner loop; (starting from 1)

[Steps of the loop structure]
① declaring a loop variable
② Judging Cycle conditions
③ execution of the loop body (operation of all code in the while {})
④ Updating loop variables
Then loop through 2, 3, 4

[Data types supported by the loop structure in JS]
①boolean:true true Flase Fake
②string: Non-empty string for vacuum string is False
③null/nan/undefined: All is False
④object: All is True
⑤number:0 is false, all non-0 are true;

While loop

While loop characteristics: First judge, then execute;

[While notation:]
var N=1;//① declaring a loop variable
while (n<=5) {//② judgment loop condition
document.write ("While Hello <br/>")//③ Execute loop body (while all code in {}) operation
N++;//④ Updating loop variables
}

Do-while Cycle
Do-while cycle characteristics: First execution, then judgment; even if the initial conditions are not established, the Do-while cycle is executed at least once;

[Do-while notation:]
var m=1;
bo=
document.write ("Do-while Hello <br/>");
m++;
}while (m<=5);



[For Loop]
1, for Loop has three expressions, respectively: ① defines the loop variable; ② judging cycle conditions; ③ Updating loop variables
Between three expressions, separated by;
For loop three expressions can be omitted, but two; not omitted
2. For loop characteristics: First judge, then execute
3, for the loop three expressions, can have a multi-part, separated by commas, but the second part of the judging conditions need to use && link, the final result needs to be true/False


for (Var x=1;x<=5;x++) {
document.write ("for Hello? <br/> ")
}

JS Basics and Loops

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.