Lesson 2 Notes
1. Judgment statement
-
If (conditional expression)
**The if statement is the most commonly used and basic * * conditional * * judgment statement. The * * value * * of the conditional judgment formula is used to determine whether * * executes a statement, or * select * which part of the statement to execute.
If (expression){
sentence
} -
if... else statement
**If... Else statement is the standard form of if statement. Based on the if statement, an * else clause * is added to execute the else statement when the value formula of the expression is * False *.
If (expression){
Statement 1
}else{
Statement 2
} -
if...else if...else
If (expression 1){
Statement 1
}Else if (expression 2){
Statement 2
}Else if (expression 3){
Statement 3
}else{
Statement n+1
} -
Mosaic of if
-
If (expression 1){
If (expression 2){
Statement 1
}else{
Statement 2
}
}else{
If (expression 3){
Statement 3
}else{
Statement 4
}
} -
while expression
The while loop statement, also known as the pre test loop statement, uses a condition to control whether to continue to execute the statement repeatedly.
While (expression){
sentence
} -
do... while statement
do... While statement is also called post test loop statement. It uses a condition to control whether to repeat the statement. Different from while, it first executes the loop statement once, and then continues to execute when judging.
do{
sentence
}While (expression)
-
for loop statement
The for loop statement, also known as the count loop statement, is generally used when the number of loops is known.
For (initialization expression; conditional expression; iterative expression){
sentence
} -
Swith statement
The switch statement is a typical multi branch statement. Its function is the same as that of the if. else.if statement, but the switch statement is more readable than the if statement. It can have the value of an expression to select the execution of different branches. Moreover, the switch statement allows the execution of a default statement when a matching condition cannot be found.switch (expression){
case constant expression:
sentence
break
case constant expression:
sentence
break
}
jump statement
-
continue Statement
Used to skip this cycle and start the next cycle
for(var i=1;i<10;i++){
if(i==6)continue
document.write('value is' + i)
} -
break statement
In a loop statement, the break statement is used to jump out of the loop.for(var i=1;i<10;i++){
if(i==6)break
document.write('value is' + i)
} -
Exception handling statement
try: the keyword you are trying to execute
Catch: keyword to catch exceptions
finally: the code that will eventually be processed. The keyword and braces can be left blank. -
Error object
The catch in the try... Catch... finally statement usually captures the Error object. When running Java Script, if errors and exceptions are generated, an Error object instance will be generated to describe the Error, which contains some specific Error information.
The Error object has the following two properties
name: string representing exception type
message: actual exception information
- throw statementactively throws an exception
Throw new error
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript"> var a=10 var b=20 if(b>a){ document.write('b greater than a') }if(b<a){ document.write('b less than a') } var a=5; if(a>5){ alert(a); }else{ alert(1); var i=1; while(i<=10){ console.log(i++); } do{ console.log(i++); }while(i<=10); for (var i=1;i<=10;i++){ console.log(i); } var i='The moon shines in front of the window' }finally { alert('The actual error message is;'+exception.message) } var i='The moon shines in front of the window' try{ document.write(str.charat(5)) }catch (exception){ alert('Program error') }finally { alert('In fact, I don't have to write') try{ document.write(str.charat(5)) }catch(exception){ </script> </head> <body> </body> </html>
2. function
-
Several usages of function
1. It is basically used as a function declaration of this score.
2. Use as a class constructor:
3. Use as closure
4. It can be used as a selector
5. Mixed application of the above four situations:
6. Use Function to process the js script returned by ajax: -
function
A function is also an object
Function can encapsulate some functions, which can be executed when needed
Use typeof to return functionWhen a function is called, the parser does not check the argument type
Pay attention to whether illegal parameters may be received. If possible, wake up and check the parameter type
Arguments to functions can be of any type
When a function is called, the parser also does not check the number of arguments
Redundant arguments are not assigned
If the number of arguments is less than the number of formal parameters, no corresponding argument will be undefined,
call
fun();
return to know that it will be returned as the result of function execution
You can accept this value with a variable
return is the last sentence in the function
If return is not followed by a value, an undefined value is returned
If return is not written in the function, undefined is returned
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript"> function fun(){ alert("I am function"); } function sum(a,b){ return a+b; } var value=sum(1,2); console.log(value) */; function sum(a,b){ return a+b; } sum(1,2); </script> </head> <body> </body> </html>
3. Execute the function immediately
Declaring a function and calling this anonymous function immediately is called immediate execution function; that is, immediate execution function is to execute the function immediately after defining the function. Immediate execution function is often executed only once, and immediate execution function will form a separate scope. We can encapsulate some temporary variables or local variables to avoid polluting Global variables
- What is the function of executing immediately
1. Change the scope of the variable (create a separate scope)
2. Encapsulating temporary variables - Other ways of writing
(function foo(){console.log("Hello World!")}())//Wrap the whole expression in parentheses and execute normally (function foo(){console.log("Hello World!")})()//Wrap the function in parentheses and execute normally !function foo(){console.log("Hello World!")}()//Use! To negate, here just want to pass the syntax check. +function foo(){console.log("Hello World!")}()//Normal execution with + -function foo(){console.log("Hello World!")}()//Use -, normal execution ~function foo(){console.log("Hello World!")}()//Use ~, normal execution void function foo(){console.log("Hello World!")}()//Use void to execute normally new function foo(){console.log("Hello World!")}()//Use new to execute normally
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript"> (function(){ alert("Execute now"); })(); (function(a,b){ alert(a+b); })(1,2); </script> </head> <body> </body> </html>
4. Array
-
Array
An array is also an object
Similar to normal object functions, it is also used to store values
The difference is that ordinary objects use strings as property names
Two arrays use numbers as index operation elements -
Indexes
Integer starting from 0
The storage performance of arrays is better than that of ordinary objects. In development, we often use hosts to store some data -
There are two ways to create arrays in JavaScript
(1) Use the Array constructor:
var arr1 = new Array(); / / create an empty array
var arr2 = new Array(20); / / create an array containing 20 items
var arr3 = new Array("lily", "lucy", "Tom"); / / create an array containing three strings
(2) Use array literal notation:
var arr4 = []; / / create an empty array
var arr5 = [20]; / / create an array containing 1 item
var arr6 = ["lily", "lucy", "Tom"]; / / create an array containing three strings -
basic function
-
1.push()
This method can add one or more elements to the end of the array and return the new length of the array -
2.pop()
This method can delete the last element of the array and return the deleted element as a return value -
3.shift()
You can delete the first element in the array and return the deleted element as the return value. If the array is empty, it returns undefined.
-
4.unshift()
Adds one or more elements to the beginning of the array and returns the new array length
Insert elements in front for a while, and the index of other elements will be adjusted backwards once. -
5.slice()
Returns a new array of items from the specified start subscript to the end subscript in the original array.
Can be used to extract specified elements from an array
This method does not change the original array, but returns the intercepted array far better than encapsulating it as a first array
parameter
The location index of the interception start, including the start index
Intercept the index at the end position, excluding the end index
The second parameter can be omitted without writing, and the index will be intercepted from the beginning to the end
The index can pass negative values. If the assignment is passed, it will be calculated from back to front
-1 penultimate - 2 penultimate -
6.splice()
Very powerful array method. It has many uses and can be deleted, inserted and replaced.
Delete: any number of items can be deleted. Only two parameters need to be specified: the position of the first item to be deleted and the number of items to be deleted. For example, splice(0,2) deletes the first two items in the array.
Insert: you can insert any number of items into the specified location. You only need to provide three parameters: starting location, 0 (number of items to be deleted) and items to be inserted. For example, splice(2,0,4,6) inserts 4 and 6 from position 2 of the current array.
Replace: you can insert any number of items into the specified location and delete any number of items at the same time. You only need to specify three parameters: starting location, number of items to delete and any number of items to insert. The number of items inserted does not have to be equal to the number of items deleted. For example, splice (2,1,4,6) deletes the entry at position 2 of the current array, and then inserts 4 and 6 from position 2.
The splice() method always returns an array containing items deleted from the original array. If no items are deleted, it returns an empty array.
parameter
1. Index indicating start position
2. Indicates the amount deleted
Third and later
You can pass some new elements, which will be automatically inserted in front of the start position index -
7.concat()
Add parameters to the original array. This method will first create a copy of the current array, then add the received parameters to the end of the copy, and finally return the newly constructed array. Without passing arguments to the concat() method, it simply copies the current array and returns a copy.
You can link two or more arrays and return the new array
It will not affect the original array -
8.join()
Group the elements of the array into a string, with separator as the separator. If omitted, use comma as the separator by default. This method only receives one parameter: separator.
This method does not affect the original array, but returns the converted String as the result -
9.reverse()
This method is used to invert the array. This method will directly modify the original array -
10.sort()
Arrange array items in ascending order -- that is, the smallest value is at the top and the largest value is at the bottom.
Can be used to sort arrays
It will also image the original array, which will be sorted according to your code by default -
11.forEach()
This method only supports browsers above IE8
Loop through the array and run the given function for each item in the array. This method has no return value. The parameters are all of function type. By default, there are passed parameters. The parameters are: the contents of the traversed array; The corresponding array index, the array itself. The foEach() method requires a function as an argument
Functions like this, which we create but do not call, become callbacks
If there are several elements in the array, the function will be executed several times. Each time, the browser will traverse the elements
Passed in as arguments, we can define formal parameters to read these contents
The first parameter is the element currently being traversed
The second parameter is the index of the element currently being traversed
The third-party parameter is the array currently traversed
-
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript"> /** * //Create array object */ var arr=new Array(); console.log(typeof arr); //Adding elements to an array //Syntax: array name [index] = value; //If you read a nonexistent index, you will not report an error, but return undefined //For non contiguous arrays, using length will get the maximum index of the array + 1 //For discontinuous arrays, use length to get the length of the array arr[0]=1; arr[1]=2; arr[2]=5; var arr2 = new Array(1,2,3,4); var arr3 = new Array(10); console.log(arr3.length); //arr.length=10; //Adds an element to the last position of the array arr[arr.length]=6; //Syntax for creating arrays using literals var sz=[1,2,3,4,5]; // console.log(typeof sz); sz=[[1,1],[2,3]]; //console.log(sz[0]); var shus=["Sun WuKong","Zhu Bajie","Sand monk"]; //push() //This method can add one or more elements to the end of the array and return the new length of the array var value=shus.push("Baigujing","spider goblin"); console.log(value); console.log(shus); //pop() //This method can delete the last element of the array and return the deleted element as a return value var zhi=shus.pop(); console.log(zhi); console.log(shus); //unshift() //Add one or more elements to the array diagram and return the new array length //Insert elements in front for a while, and the index of other elements will be adjusted backwards once. var le=shus.unshift("Tang Monk","White dragon horse"); console.log(le); console.log(shus); //shift() //You can delete the first element in the array and return the deleted element as a return value var res=shus.shift(); console.log(res); console.log(shus); </script> </head> <body> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript"> //Array traversal var arr=[1,2,3,4,5,7]; /* for(var i=0;i<arr.length;i++){ console.log(arr[i]); } */ /* Generally, the for loop is used to traverse the array JS A method is also provided to traverse the array forEach() This method only supports browsers above IE8 foEach()Method requires a function as an argument Functions like this, which we create but do not call, become callbacks If there are several elements in the array, the function will be executed several times. Each time, the browser will traverse the elements Passed in as arguments, we can define formal parameters to read these contents The first parameter is the element currently being traversed The second parameter is the index of the element currently being traversed The third-party parameter is the array currently traversed */ /* arr.forEach(function(value,index,obj){ //console.log(value); }); */ //slice() //Can be used to extract specified elements from an array //This method does not change the original array, but returns the intercepted array far better than encapsulating it as a first array //parameter //The location index of the interception start, including the start index //Intercept the index at the end position, excluding the end index //The second parameter can be omitted without writing, and the index will be intercepted from the beginning to the end //The index can pass negative values. If the assignment is passed, it will be calculated from back to front //-1 penultimate - 2 penultimate /* var arr=[1,2,3,4,5,6,7]; var sz=arr.slice(1,-1); console.log(sz); */ //splice() //You can delete the specified element in the array //Using splice() will image the original array and delete the specified element from the original array //And return the deleted element as a return value //parameter //1. Index indicating start position //2. Indicates the amount deleted //Third and later //You can pass some new elements, which will be automatically inserted in front of the start position index //arr.splice(2,0,10,20,30); //console.log(arr); //concat() can link two or more arrays and return the new array //No paste has an impact on the original array var arr=[1,2,3,4,5,6,7]; var arr1=[9,8,7]; var sz=arr.concat(arr1,11,22,33); console.log(sz); //join() //This method can convert the array to a string //This method does not affect the original array, but returns the converted String as the result //In join(), you can specify a string as a parameter to link all the elements in the array //If no parameter is specified, '' is used as the link character by default var value=arr.join("@"); console.log(typeof value); console.log(value); //reverse() //This method is used to invert the array. This method will directly modify the original array arr.reverse(); console.log( arr); //sort() //Can be used to sort arrays //It will also image the original array, which will be sorted according to your code by default arr.sort(); //console.log( arr); //For pure numeric arrays, use sort(). Also sort by Unicode encoding //So we may get the wrong result //We can customize the sorting rules //You can add a callback function to sort() to make rules arr=[2,1,3,2,5,4,6]; arr.sort(function(a,b){ if(a>b){ return -1; }else if(a<b){ return 1; }else { return 0; } return a-b; }); console.log(arr1); </script> </head> <body> </body> </html>
Exercises
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript"> Frog climbing well /* var i=0; var n=1; while(i<10){ i+=5; if(i>=10)break; i-=4; console.log(n++); } */ /* var gao=0; var tianSe=true; var num=0; do{ if(tianSe){ gao=gao+5; tianSe=false; }else{ gao=gao-4; tianSe=true; num++; } }while(gao<10); /* * *** ***** ******* ********* */ console.log(num); */ /* var row=5; // row Indicates the total number of rows for(var r=1;r<=row;r++){ //The number of outer loop control lines r represents the number of lines per change var triangle=""; //triangle Represents the last triangle for(var space=r;space<row;space++){ //This loop controls the number of spaces. space represents the number of spaces triangle+=" "; } for(var star=1;star<=2*r-1;star++){ //The loop control * number star represents * number triangle+="*"; } console.log(triangle); } */ /* for(var row=1;row<=5;row++){ for(var a=1;a<=5-row;a++){ document.write(" "); } for(var star=1;star<=2*row-1;star++){ document.write("*") } document.write("<br/>"); } */ /*A hundred dollars for a hundred chickens */ for(var cockNum = 0; cockNum<= 19; cockNum++){ for(var henNum = 0; henNum <= 33; henNum++){ var poultNum = 100 - cockNum - henNum; if((cockNum * 5 + henNum * 3 + poultNum * (1/3) === 100) && poultNum % 3 === 0){ console.log("Number of cocks available:" + cockNum); console.log("Number of hens available:" + henNum); console.log("Number of chicks you can buy:" + poultNum); } } } </script> </body> </html> </script> </head> <body> </body> </html>