js basic knowledge summary

Posted by PHPLRNR on Sun, 30 Jan 2022 12:12:20 +0100

catalogue

1, Data type

1. Forced conversion type:

2, Operator

Unary operator:

Self increasing and self decreasing:

Logical operators:

Assignment operator:

Relational operators:

Equality operator:

Conditional operator:

Process control statement:

3, Object

Function:

Prototype object:

Array

Date:

Math object:

                  

                       

1, Data type

Number Boolean Null Undefined

1. Forced conversion type:

①. Convert to Number
②. Other hexadecimal digits
Hex: a = 0X10
Octal: a = 070
Like this 070, when we use parseInt for conversion, some browsers will treat it as an octal number, which is 56
Some browsers treat it as an ordinary 070, that is, the decimal system, which is converted to 70

So in order to specify it, we need to add 10 or 8 ↓
a = "070"
a = parseInt(a,10)====70
a = parseInt(a,8)====56

a = "070"
a = parseInt(a,8)
console.log(typeof a)
console.log(a)

 


In js, if you need to represent the number prohibited by 16, you need to start with 0X,
If you need to represent an octal number, you need to start with 0,
If it represents a binary number, it needs to start with 0b, but not all browsers support it
 

Convert to Boolean
//
Using the Boolean() function
Number - > Boolean
All are true except 0 and NaN

var a = 123;
// Call the Boolean() function to convert a to a Boolean value
a = Boolean(a)
console.log(a)
console.log(typeof a)

-----true
-----boolean
===========================
var a = 0;
// Call the Boolean() function to convert a to a Boolean value
a = Boolean(a)
console.log(a)
console.log(typeof a)

-----false
-----boolean
===========================
var a = NaN;
// Call the Boolean() function to convert a to a Boolean value
a = Boolean(a)
console.log(a)
console.log(typeof a)

-----false
-----boolean
===========================
var a = Infinity;
// Call the Boolean() function to convert a to a Boolean value
a = Boolean(a)
console.log(a)
console.log(typeof a)

-----true
-----boolean


String ----- > Boolean
All are true except empty string
Both null and undefined are converted to false
The object is also converted to true

var a = "Hello JS"
//Use the Boolean() function to convert a to a Boolean value
a = Boolean(a)
console.log(a)
console.log(typeof a)

-----true
-----boolean
===========================

var a = "" <----Empty string
//Use the Boolean() function to convert a to a Boolean value
a = Boolean(a)
console.log(a)
console.log(typeof a)

-----false
-----boolean
===========================
var a = " "
//Use the Boolean() function to convert a to a Boolean value
a = Boolean(a)
console.log(a)
console.log(typeof a)

-----true
-----boolean
===========================
var a = null
//Use the Boolean() function to convert a to a Boolean value
a = Boolean(a)
console.log(a)
console.log(typeof a)

-----false
-----boolean
===========================
var a = undefined
//Use the Boolean() function to convert a to a Boolean value
a = Boolean(a)
console.log(a)
console.log(typeof a)

-----false
-----boolean
===========================

2, Operator

Operators are also called operators
Operators can operate on one or more values and obtain the operation results
For example, typeof is an operator that can obtain the type of a value, and it will return the type of the value as a string
number string boolean  undefined null object
Arithmetic operator
When values of non Number type are evaluated, they are converted to Number and then evaluated
 result = 2 + null
Result = 2 + NaN < = = = = any value and NaN are calculated, and the result is NaN
+ you can add two values and return the result as , result = true + 1
 

var result = 2 + null
console.log("result="+result)

------result = 2
 here null For non Number Value of type, first null Convert to Number The value is 0, and then the result is 2,
This is equivalent to this operation↓
var a = null
a = Number(a)
console.log(a)
---------0

var result = 2 + NaN
console.log("result="+result)
-------NaN

var  result = true + 1
console.log(result)
-----------2
 Convert Boolean values to number The value is 1


 
If you add two strings, the two strings will be spliced, spliced, spliced into a string and returned. result = "hello" + "tomorrow"
Any value and string will be converted into a string before being concatenated with the string,

result = "Hello"+"tomorrow"
console.log("result="+result)
------result=Hello tomorrow

result = "Hello"+1
console.log("result="+result)
------result=Hello 1


 result = 1+2+"3"
console.log(result)
-------33

 
We can use this feature to convert any data type into String. We only need to add a "" to any data type to convert it into String
This is an implicit type conversion, which is automatically completed by the browser. In fact, it also calls the String() function
   ↑var c = 123
    c = c + ""; <=======> c = String(c);
 

var c = 123
console.log(typeof c)   -----number
c = c+""
console.log(typeof c)   -----String


 - 
- you can subtract two values and return the result to result = 100 - "1" = = = 99
 *
 / 
Any value and - * / are automatically converted to Number
We can use this feature for implicit type conversion. We can convert it to Number by converting it to a value of - 0 * 1 / 1
The principle is the same as that of the Number() function, but it is simpler to use

var result = "1"
console.log(typeof result)  ------string
 result = "1"-0
 console.log(typeof result) ------number


 %
Modulo operation (remainder)

var a = 9%4
console.log(a)
------1


Unary operator:

Only one operand is required
+Plus sign
+ no effect on numbers
-Minus sign
- you can reverse the negative sign of a number
    

var a = 123
 a = -a
 console.log("a="+a) ===-123


For values of non Number type, it will be converted to Number before operation
You can use + on another data type to convert it to number
It works the same way as the Number() function

var b = "123"
console.log(typeof b)  ------string
b = +b
console.log(typeof b)  ------number

Self increasing and self decreasing:

Self increasing++
Through self increment, the variable can be increased by 1 on its own basis. For a variable, after self increment, the value of the original variable will increase by 1 immediately
There are two types of auto increment: Post + + (a + +) and pre + + (+ + a)
Either a + + or + + a will immediately increase the value of the original variable by 1
The difference is that the values of a + + and + + a are different
The value of a + + is equal to the value of the original variable (the value before self increment)

var c = 10;
// For the first time, c + + increases automatically on the basis of 10. At this time, c is 11. For the next time, it increases automatically on the basis of 11 ↓
console.log(c++) -------------------10
console.log(c)   -------------------11
// The second time, c + + is self increasing on the basis of 11. At this time, c is 12
console.log(c++) -------------------11
console.log(c)   -------------------12


++The value of a is equal to the new value of the original variable (the value after self increment)
          

 var d = 20;
 console.log(++d)  ====21
 console.log(d)    ====21 

Look where the + sign is. Add 1 first in the front and 1 later in the back. + + essentially increases the original value. A + + assigns value first and then increases itself, + a adds value first and then assigns value

Self subtraction -- the principle is the same as above

var d = 20
          20  + 22 +22 
result = d++ + ++d +d
d++Is 20, at this time d Is 21,++d,Self increase first, so self increase on the basis of 21,++d Is 22, at this time d Also 22,
console.log("result="+result)    -------64

Logical operators:

JS provides us with three logical operators
! wrong
    ! Can be used to perform non operations on a value
The so-called non operation refers to the inverse operation of a Boolean value
If you negate a value twice, it will not change


If you operate on a non Boolean value, it is converted to a Boolean value and then reversed
We can use this feature to convert another data type to Boolean value
An arbitrary data type can be inverted twice to convert it to a Boolean value
The principle is the same as that of Boolean() function
&&And
You can sum the values on both sides of the symbol and return the result
   
If both values are true, it will return true. If there is one false, it will return false

     var result = true&&true
      console.log(result)     =======true


    var result = true&&false
      console.log(result)     =======false

   var result = false&&false
      console.log(result)     =======false

||Or
You can or operate on the values on both sides of the symbol and return the result
Operation rules: both are false, and the result is false. As long as there is one true, the result is true
    
    

var result = false || true
console.log(result)      ======true

var result = false || false
console.log(result)      =====false

var result = true || true
console.log(result)      =====true


Non Boolean case
When an or operation is performed on a non Boolean value, it is converted to a Boolean value, then the operation is performed, and the original value is returned
And operation: if both values are true, the following value is returned
  

  var result = 1 && 2;
    console.log("result="+result) =====>2


If one value is false, the value of false is returned

    result = 2 && 0
    console.log("result="+result)=======>0


If both values are false, the previous value is returned

    result = NaN && 0
    console.log("result="+result)=======>NaN


Summary:
And operation: if the first value is true, the second value (& &) must be returned
If the first value is false, the first value is returned directly

(in the and operation, true will be returned only if both are true, and false will be returned as long as there is one false.)
Or operation: if the first value is true, the first value will be returned directly, (||),

If the first value is false, the second value is returned directly

(because as long as one value in the or operation is true, it will return true. If the first value is true, it doesn't have to look at the second one. The second one will return true regardless of true or false)
(the first one is already false. If the second one is true, it will return true. If it is false, it will return false, so whoever it is will directly return the second value)

Assignment operator:

=
The value on the right side of the symbol can be assigned to the variable on the left side of the symbol

var a = 123;
console.log(a) 
//Assign 123 to a

+=
a = a +5
Equivalent to a+=5
-=
a = a-5 is equivalent to a-=5
*=
a=a*5 is equivalent to a*=5
/=
a=a/5 is equivalent to a/=5
%=
a = a*%5 is equivalent to a%=5

Relational operators:

Through relational operators, you can compare the size relationship between two values
Returns true if the relationship is established, and false if the relationship is not established

>Greater than sign
Judge whether the value on the left side of the symbol is greater than that on the right side. If the relationship is established, return true. If the relationship is not established, return false

var result = 5>10
console.log(result)
====false


>=Greater than or equal to
Judge whether the value on the left of the symbol is greater than or equal to that on the right. If the relationship is established, return true; if the relationship is not established, return false
< less than sign

Judge whether the value on the left of the symbol is less than that on the right. If the relationship is established, return true. If the relationship is not established, return false

< = less than or equal to

Judge whether the value on the left of the symbol is greater than or equal to that on the right. If the relationship is established, return true; if the relationship is not established, return false

Non numerical case
For non numerical cases

console.log(1>true) false
console.log(1>=true) true
console.log(1>="0")  true
console.log(1>=null) true
console.log(1>="hello") false

The above will convert the value to a numerical value and then compare it
"hello" is converted to the value type NaN, and any value compared with NaN is false
 

console.log(true>false) true
console.log(11<"5") false


If the values on both sides of the symbol are strings, they will not be converted to numbers for comparison, but the Unicode encoding of the characters in the string will be compared respectively

console.log("11"<"5")
↑ 1 Compare with 5 first,1 If the character code is less than 5, there is no need to compare it later. It is directly less than the sign, even if it is
console.log("132233"<"5")It's also a less than sign, because the first one has decided the size

If you compare two string numbers, you may get unexpected results,
Note: when comparing two string numbers, be sure to transform

When comparing two strings, the character encoding of the string is compared

When comparing character codes, they are compared bit by bit. If the two bits are the same, the next bit is compared, so it is used to sort English

console.log("a"<"b") true

console.log("abc"<"b") true

Comparing Chinese is meaningless
console.log("you > me")
Use escape characters to enter unicode encoding in a string
\u four bit coding
console.log("\u0031") --------1

Use Unicode &# encoding in web pages; The encoding here needs to be decimal
 

<h1>&#1;</h1>
<h1>&#2620;</h1> 
//2620 hexadecimal, which has to be converted to decimal


<h1>&#2620;</h1>
<h1 style="font-size: 100px;">&#9760;</h1>

Equality operator:

It is used to compare whether two values are equal. If equal, it returns true. If unequal, it returns false. Use = = for equality operation
When = = is used to compare two values, if the types of values are different, it will be automatically converted to the same type, and then compared

console.log(1==1)    -----true

var a = 10
console.log(a==10)   -----true

console.log("1"==1)   true Convert string 1 to number 1
console.log(true=="1") true



console.log(null==0) false ,in principle null Turn into Number 0, 0==0,The result should be true,however
 This is a special case and the result is false,Not converted into number. . 

undefined is derived from null, so when these two values are judged to be equal, it will return true

console.log(undefined==null)
---true


NaN is not equal to any value, including itself

console.log(NaN==NaN) ====false

var b = NaN
Judge whether the value of b is NaN
console.log(b==NaN) this method does not work

You can use the isNaN() function to determine whether a value is NaN. If the value is NaN, it returns true

var b = NaN
console.log(isNaN(b))   ----true

Unequal:

It is used to judge whether two values are not equal. If they are not equal, it returns true, and if they are equal, it returns false
Use= To do inequality
Unequal variables will also undergo automatic type conversion. If they are equal after conversion, false will be returned

===
Congruent
It is used to judge whether two values are congruent. It is similar to equality. The difference is that it will not carry out automatic type conversion. If the types of two values are different, it will directly return false
 

   console.log("123"==123) true
    console.log("123"===123)false


!==
Incomplete equivalence
It is used to judge whether two values are not congruent. It is similar to different values. The difference is that it will not carry out automatic type conversion. If the types of two values are different, it will also return true
  

 console.log("1"!=1) false
    console.log("1"!==1) true

Conditional operator:

Also called ternary operator

Syntax:
Conditional expression? Statement 1: Statement 2;
Process performed:
When executing a conditional operator, first evaluate the conditional expression. If the value is true, execute statement 1 and return the execution result. If the value is false, execute statement 2 and return the execution result
true?alert('right '): alert('wrong')
If the expression of a condition evaluates to a non Boolean value, it is converted to a Boolean value before the operation


Operator priority: same as math
Multiplication and division before addition and subtraction

var result = 1+2*3
console.log(result)  ====7

If the priority of 𞓜 is high, or both are equally high, 3 should be returned
If the priority is higher than or equal to, 1 should be returned

var result = 1||2&&3;
console.log(result)====1

There is a table of symbol priority in js. The higher the priority in the table, the higher the priority, the more priority operation. If the priority is the same, the operation will be carried out from left to right
This table does not need to be memorized. If the priority is unclear, you can use () to change the priority

var result = 1||(2&&3);
console.log(result)====1

var result = (1||2)&&3;
console.log(result)====3

operator
Using, you can split multiple statements, which can generally be used when declaring multiple variables
var a;
var b;
var c;
Use the operator to declare multiple variables at the same time,
var a,b,c
Use the operator to declare multiple variables and assign values at the same time
var a=1,b=2,c=3

Code block
Our program consists of statements one by one
Statements are executed one by one from top to bottom,
In js, {} can be used to group statements
The statements in the same {} become a group of statements. They either execute or do not execute,
The statement in a {} is also called a code block
There is no need to write after the code block; Yes
The code block in js only has the function of grouping and has no other purpose. The content inside the code block is completely visible from the outside

Process control statement:


We all know that the program in JS is executed line by line from top to bottom,
alert('hello')
console.log("hello")
Click the pop-up box to output Hello

Through the process control statement, we can control the execution process of the program, so that our program can choose to execute according to certain conditions
Classification of statements:
1. Conditional judgment statement
2. Conditional branch statement
3. Circular statement

1, Conditional judgment statement:


Using conditional judgment statements, you can judge before executing a statement. If the condition is true, the statement will be executed, and if the condition is not true, the statement will not be executed
if statement
① Syntax:

if(Conditional expression){
    sentence
}


if(true){
   alert('Hee hee')
 }


When the if statement is executed, the conditional expression will be evaluated first. If the value of the conditional expression is true, the statement after if will be executed. If the value of the conditional expression is false, the statement after if will not be executed,

        

        var  a = 10
        if(a>1)
        alert('a Larger than 1')

The if statement can only control the following statement,
      

        var  a = 10
        if(a>1)
        alert('a Larger than 1')
        alert('Don't mind me')
-----The browser will only pop up'a Larger than 1'No statement below it will pop up


If you want if statements to control multiple statements, you can unify these statements into code blocks
    

        var  a = 10
        if(a>1){
        alert('a Larger than 1')
        alert('Don't mind me')
        }


--------use{}If the code block is wrapped, the content inside can be executed

The code block after the if statement is not necessary, but try to write the code block in the development, even if there is only one statement after the if statement

var a = 15
if(a>10&&a%<20){
    alert('nnnnn')
}

② Syntax:

if(Conditional expression){
    sentence...
}else{
    sentence...
}


if...else... sentence
When the statement is executed, the conditional expression after if will be evaluated first. If the value is true, the statement after if will be executed; if the value is false, the statement after else will be executed
      

         var age = 60
        if(age>=60){
            console.log('retire')
        }else{
            console.log('go to work')
        }

------Output retirement


③ Syntax:

if(Conditional expression){
    sentence...
}else if(Conditional expression){
    sentence...
}else if(Conditional expression){
    sentence...
}else{
    sentence...
}    


if ...else if ... else
When the statement is executed, the conditional expression will be evaluated and judged from top to bottom. If the value is true, the current statement will be executed. If the value is false, continue to judge downward,
If all conditions are not met, the last else statement will be executed. In this statement, only one code block will be executed. Once the code block is executed, the statement will be ended directly
 

if exercise
The return value of the prompt() function is of type String
Write a program, input three integers from the keyboard, store them in variables num1, num2 and num3 respectively, sort them, and output them from small to large

var num1 = +prompt('Please enter the first number')        //Because the prompt() function returns a string type, it needs to be converted to
var num2 = +prompt('Please enter the second number')        //number type, so add one before prompt+   
var num3 = +prompt('Please enter the third number')

if(num1<num2&&num1<num3){
    if(num2<num3){
        console.log(num1+","+num2+","+num3)
    }else{
        console.log(num1+","+num3+","+num2)
    }
}else if(num2<num1&&num2<num3){
    if(num1<num3){
        console.log(num2+","+num1+","+num3)
    }else{
        console.log(num2+","+num3+","+num1)
    }
}else{
    if(num2<num1){
        console.log(num3+","+num2+","+num1)
    }else{
        console.log(num3+","+num1+","+num2)
    }
}

2, Conditional branch statement:

Also called switch statement
Syntax:

switch(Conditional expression){
case expression:
    sentence...
    break;
case expression:
    sentence...
    break;
case expression:
    sentence...
    break;
case expression:
    sentence...
    break;
default: 
    sentence...  
    break;
}

Execution process:
switch...case.. sentence
During execution, the value of the expression after case and the value of the conditional expression after switch will be compared in sequence
If the comparison result is true, the code will be executed from the current case
The code after the current case will be executed. We can follow the case with a break keyword, which can ensure that only the statements after the current case will be executed and no other cases will be executed

         var num = 1;
            switch(num){
            case 1:
            console.log("①")     
            case 2:
            console.log("②")
        }
        The first one didn't break,It will output in turn①②,But we just want①
   ==============//Use break to exit the switch statement, and the statement after break will not be executed
        var num = 1;        
        switch(num){
            case 1:
                console.log("①")     
                break;
            case 2:
                console.log("②")
                break;
            default:
                console.log('Illegal number')
                break;
        }

=======output①


If the comparison result is false, continue the downward comparison
If all the comparison results are false, only the statements after default will be executed
The functions of switch statement and if statement are actually repeated. Using switch can realize the functions of if. Similarly, using if can realize the functions of switch,
So we can choose according to our habits

var score = 25
		switch(parseInt(score/10)){
			case 10:
			case 9:
			case 8:
			case 7:
			case 6:
				console.log('qualified');
				break;
			default:
				console.log('unqualified')
				break;
		}
		
	switch(true){
			case score>=60:
			console.log('qualified');
				break;
			default:
				console.log('unqualified')
				break;
		}

Circular statement:

A piece of code can be executed repeatedly through circular statements
Output consecutive numbers to the page
while Loop

while(Conditional expression){
    sentence...
}


When executing a while statement, first evaluate and judge the conditional expression. If the value is true, the loop body will be executed. After the loop body is executed, continue to judge the expression. If it is true, continue to execute the loop body, and so on
If the value is false, the loop is terminated

A loop that writes a conditional expression to true is called an endless loop. The loop will not stop unless the browser is closed. The endless loop should be used with caution in development
You can use break to terminate the loop

while(true){
    alert(n++)
    judge n Is it 10
    if(n==10){
        //Exit loop
        break;
    }
    
}


Create a loop:
1. Initialize a variable
var i = 0
2. Set a conditional expression in the loop
while(i<10){
    alert(i)

/ / 3. Define an update expression to update the initialization variable each time
    i++;
}

Create a while loop that executes 10 times
Initialization expression
var i = 0;
Create a loop body and define a conditional expression
while(i<10){
Set update expression
    alert(i++)
}

do... while Loop

do{
    sentence...
}while(Conditional expression)


do{         
   document.write(i++ +"<br/>")
}while(i<=5000)


do... When the while statement is executed, the loop body will be executed first. After the loop body is executed, the conditional expression after while will be judged,
If the value is true, the loop body will be executed. After the execution of the loop body, continue to judge the expression. If it is false, the loop will be terminated
In fact, the functions of these two statements are similar. The difference is that while is judged before execution, while do While is execution before judgment,
do...while can ensure that the loop body is executed at least once, while while cannot

while exercise:
If the annual interest rate of the investment is 5%, how many years will it take to increase from 1000 yuan to 5000 yuan?

var money = 1000;
var count = 0;
while(money<5000){
    money *=1.05;
    count++ 
}
console.log(count)

for loop
The for statement is also a loop statement, also known as a for loop
In the for loop, there is a special place to store three expressions
1. Initialization expression
2. Conditional expression
3. Update expression syntax:

for(Initialization expression;Conditional expression;Update expression){
    sentence...
}
 for(var i = 0;i<10;i++){
        alert(i)
    }

for loop execution process:
① Initialization expression, initialization variable (initialization expression will be executed only once)
② Conditional expression to judge whether to execute the loop. If it is true, execute the loop statement ③. If it is false, terminate the loop
④ Execute the update expression. After the update expression is executed, continue to repeat ②


All three parts of the for loop can be omitted or written externally,
If you don't write any conditions, just write two semicolons. At this time, the loop is an endless loop

for(;;){
    alert('hhh')
}

var i = 0;
for(;i<10;){
    alert(i++)
}

Receive a number entered by the user in the page and judge whether the number is a prime number
Prime number: a number that can only be divided by 1 and itself. 1 is neither a prime number nor a composite number. A prime number must be a natural number greater than one

var num = prompt("Please enter an integer greater than 1");
			// Judge whether this value is legal
			if(num<1){
				alert('wrongful')
			}else{
				// Create a variable to save the status of the current number
				// The default current num is prime
				var flag = true;
				// Judge whether num is a prime number
				// Gets the number between 2-num
				
				for(var i = 2;i<num;i++){
					// console.log(i)
					// Determine whether num can be divided by i
					if(num%i==0){
						// If num is divided by i, Num must not be prime
						// Set flag to false
						flag = false;
					}
				}
				// Output if num is prime
				if(flag){
					alert(num+"Is a prime number")
				}else{
					alert('Not prime')
				}
				
			}

Nested for loop
1. Output graphics through a for loop
How many times does the for loop execute? What is the height of the graph
It can be used to control the height of graphics
for(var i = 0;i<5;i++){
    document.write("*****<br/>")
}

            for(var i = 0;i<5;i++){
				document.write("*")
			}
			document.write("<br/>")

//The external for loop executes once. Internal execution five times

for(var i = 0;i<5;i++){
    Create another loop inside the loop to control the width of the drawing
    The inner loop can be used to determine the width of the figure. The width is the number of times it is executed
    for(var j = 0;j<5;j++){
        document.write("*****<br/>")
    }
}

            for(var i =0;i<5;i++){
				for(var j = 0;j<5;j++){
					document.write("*&nbsp;&nbsp;&nbsp;&nbsp;")
				}
				document.write("<br/>")//The inner loop is executed five times, the outer loop is executed once, and the line is wrapped five times
			}

            for(var i = 0;i<5;i++){
				for(var j = 0;j<i+1;j++){
					document.write("*&nbsp;&nbsp;")
				}
				document.write("<br/>")
			}

 

            for(var i = 0;i<5;i++){
				for(var j =0;j<5-i;j++){
					document.write("*&nbsp;&nbsp;&nbsp;")
				}
				document.write("<br/>")
			}

99 multiplication table:

             for(var j =1;j<=9;j++){
				for(var i = 1;i<=j;i++){
					document.write("<span>"+i+"*"+j+"="+j*i+"</span>")
				}
				document.write("<br/>")
			}



            <style type="text/css">
			span{
				display: inline-block;
				width: 100px;
				/* height: 80px; */
				border: 1px solid red;
			}
		    </style>

break and continue

The break keyword can be used to exit a switch or loop statement (break or continue cannot be used in an if statement)
The break keyword will immediately terminate the loop statement closest to it
You can create a label for the loop to identify the current loop
label: Circular statement
When using the break statement, you can follow a label after the break, so that the break will end the specified loop instead of the nearest one

for(var i = 0;i<5;i++){
    console.log(i)
    break
}
 ------0


As soon as the break is executed, the loop ends immediately
 

 if(true){
    break   ---------Will report an error(if Statement cannot be used break or continue)
    console.log('hello')
 }


 

 for(var i = 0;i<5;i++){
    console.log(i)
    if(i==2){
        break;    -------there break yes for Circulation works
    }
}
-----0 1 2

        

            outer: 
            for(var j =1;j<=5;j++){
                console.log("Outer circulation"+j)
                for(var i = 1;i<=j;i++){
                break outer;   ------Terminate outer layer for loop
                    console.log("inner loop "+i)
                }
            }


            
The continue keyword can be used to skip the current cycle

for(var i = 0;i<5;i++){
    if(i==2)
    continue;
}
console.log(i)
---0 1  3 4
for(var i = 0;i<5;i++){
    if(i==2)
    break;
}
console.log(i)
---0 1 

Similarly, continue also works on the circular statement closest to him

Find prime numbers within 100

Gradual improvement of performance

Test the performance of the following programs
Start the timer when the program is executing
console.time("name of timer") can be used to start a timer
 
He needs a string as a parameter, which will be used as the identification of the timer
console.time('test');
Stop timers
console.timeEnd() is used to stop a timer. A timer name is required as the parameter ''
console.timeEnd('test');
Start and end with the same name

You can use math Sqrt() squares a number

             console.time('test')
             for(var i = 2;i<=10000;i++){
			 	var flag = true
			 	for(var j = 2;j<i;j++){
			 		if(i%j==0){
			 			flag = false
			 		}
			 	}
			 	if(flag){
			 		console.log(i)
			 	}
			 }
             console.timeEnd('test')
              
             console.time('test')
             for(var i = 2;i<=10000;i++){
			 	var flag = true
			 	for(var j = 2;j<i;j++){
			 		if(i%j==0){
			 			flag = false
                        break;
			 		}
			 	}
			 	if(flag){
			 		console.log(i)
			 	}
			 }
             console.timeEnd('test')

             console.time('test')
             for(var i = 2;i<=10000;i++){
			 	var flag = true
			 	for(var j = 2;j<Math.sqrt(i);j++){
			 		if(i%j==0){
			 			flag = false
                        break;
			 		}
			 	}
			 	if(flag){
			 		console.log(i)
			 	}
			 }
             console.timeEnd('test')

3, Object

Data types in JS:
Basic data type:

String string Number numeric Boolean Boolean Null null Undefined undefined
As long as the values we see are not the above, they are all objects
Reference data type:

Object object
The basic data type is a single value 123 true 'hello', and there is no relationship between the value and the value
Represent a person's information (name, age, gender) in js
var name = "Zhang San",
var age = 3,
var gender = "male"
If the basic data type is used, the variables we create are independent and cannot be a whole,
Object belongs to a composite data type, in which multiple attributes of different data types can be saved

Classification of objects:
    1. Built in object
Objects defined by ES standards can be used in any implementation of ES
For example, Math Function String Number Boolean, etc...
    2. Host object
At present, the objects provided by the running environment of JS mainly refer to the objects provided by the browser
For example, BOM DOM console log document. write
    3. custom object
Objects created by developers themselves

create object

var obj = new Object();
console.log(obj)
console.log(typeof obj)

The function called with the new keyword is the constructor,
Constructors are functions designed to create objects
When you use typeof to check an object, object is returned

Values saved in objects are called properties
Add attributes to objects
Syntax: objects Attribute name = attribute value
Add a name attribute to obj
obj.name = "Zhang San"

Read properties in object
Syntax: objects Attribute name
console.log(obj.name)
If we read a property that does not exist in our object, we will not report an error, but will return undefined

Modify the attribute value of an object
Syntax: objects Attribute name = new value

Delete an object's properties
Syntax: delete object Attribute name

var obj = new Object()
//Add attribute
obj.name = "Zhang San"
obj.age = 3
obj.gender = "male"
console.log(obj)

//Delete attribute
delete obj.name
console.log(obj)
//modify attribute
obj.age = 3
console.log(obj)
//get attribute
console.log(obj.name)

Attribute name:
The attribute name of the object is not required to comply with the specification of the identifier. Any name can be used, but try to follow the specification of the identifier

obj.var = "hello"
console.log(obj.var)
//You can also use the keyword var

If a special attribute name is used, it cannot be used The way to operate
Another method is required:
Syntax: Object ["attribute name"] = attribute value
This method should also be used when reading
Using [] to manipulate attributes is more flexible
You can directly pass a variable in [], so that the number of variable values will read which attribute

obj["hahah"] = "What are you laughing about?"
var n = "hahah"
console.log(obj[n])  // -----What are you laughing at

obj["123"] = 789
console.log(obj["123"])   //-----789

Attribute value:
The attribute value of JS object can be any data type, or even it can be an object

obj.test = true
obj.test = null
obj.test = "hello"
obj.test = 123
console.log(obj.test)

            var obj = new Object();
            // console.log(typeof obj)
            obj.name = "Zhang San"
            obj.age = 15
            obj.gender = "male"
            obj.name = "Reese"
            // delete obj.name
            // console.log(obj.name)  undefined
            var obj2 = new Object();
            obj2.name = "Ha ha ha"
            obj.name = obj2
            console.log(obj)
            console.log(obj.name)   //Ha ha ha


in operator
This operator allows you to check whether an object contains a specified attribute
If true is returned, false is not returned
Syntax:
Attribute name in} object
console.log("test" in obj)

Data types in JS
Basic data type: String string Number value Boolean Boolean value Null null value Undefined undefined
Reference data type: Object object
The variables in JS are stored in stack memory,
The value of the basic data type is stored directly in the stack memory,
Values exist independently of each other. Modifying one variable will not affect other variables

Objects are saved in heap memory. Every time a new object is created, a new space will be opened in heap memory,
Variables save the memory address of the object (object reference). If two variables save the same object reference
When a property is modified through one variable, the other is also affected

When we compare the values of two basic data types, we compare the values. When we compare two reference data types, we compare the memory address of the object,
If two objects are as like as two peas, but the address value is different, they will return to false.

Object literal:
Use object literals to create an object

var obj = new Object();
//Equivalent to ↑↓
var obj = {};
console.log(obj)

Using object literals, you can directly specify the properties of an object when creating an object,
The attribute name of an object literal can be quoted or not. It is recommended not to add quotation marks,
If you want to use some special names, you must add
"$%^%Y"
Attribute names and attribute values are a set of name value pair structures (key value pairs)
Names and values are connected by colons, and multiple name value pairs are separated by colons,
If there are no other attributes after an attribute, you don't need to write it
Syntax:
{property name: property value, property name: property value...}
var obj2 = {name: "Zhang San"}

Function:

function
A function is also an object
document console...
Everything is an object
Some functions (code) can be encapsulated in functions and can be executed when needed
Some code can be saved in the function and called when needed
When typeof is used to check a function object, function is returned
Create a function object

You can pass the code to be encapsulated to the constructor as a string

Code encapsulated in a function is not executed immediately
The code in the function will be executed when the function is called
Call function:
Syntax:
Function object ()
When a function is called, the code encapsulated in the function is executed in order
fun()

var fun = new Function("console.log('hello,This is my first function')");
console.log(fun)
fun()

-------
However, in our actual development, we rarely use constructors to create a function object
-------
Use function declarations to create a function
Syntax:
Function function name ([parameter 1, parameter 2,... Parameter N]){
Statement
    }
--------
             

                function fun2(){
                    console.log("This is the first function I encapsulated")
                    alert('Ha ha ha ha')
                    document.write('hey')
                }
                console.log(fun2)  //Print function
                fun2()//Execution function


--------
Use a function expression to create a function
var function name = function([formal parameter 1, formal parameter 2,... Formal parameter N]){
Statement
    }
  

  function(){
        console.log("I am the code encapsulated in anonymous functions")
    }


======    
  

  var fun3 = function(){
        console.log("I am the code encapsulated in anonymous functions")
    };
    fun3()


------
Parameters of function
Define a function to find the sum of two numbers
You can specify one or more formal parameters (formal parameters) in () of the function. Multiple formal parameters are separated by
Declaring a formal parameter is equivalent to declaring the corresponding variable inside the function, but does not assign a value
When calling a function, you can specify arguments (actual parameters) in ()
The actual parameter will be assigned to the corresponding formal parameter in the function

function sum(a,b){
    console.log(a+b)   //7
}
sum(3,4)

When a function is called, the parser does not check the type of the argument
Therefore, you should pay attention to whether illegal parameters may be received. If possible, you need to check the type of parameters,
The arguments of a function can be any data type
When calling a function, the parser will not check the number of arguments, and the extra arguments will not be assigned
If the argument is smaller than the formal parameter, the formal parameter without corresponding argument will be undefined
-------
Return value of function
Create a function to calculate the sum of three numbers
You can use return to set the return value of the function
Syntax:
return value
The value after return will be returned as the execution result of the function. You can define a variable to receive the result

Call function
The value of the variable result is the execution result of the function
The result value returned by the function is what it is,
In the function, the statements after return will not be executed,

If the return statement is not followed by any value, it is equivalent to returning an undefined
If return is not written in the function, undefined return will also be returned, which can be followed by any type of value

            function sum(a,b,c){
			    var d = a+b+c
			    return d;
			    alert('hello')    //----Do not execute
			}
			var result = sum(1,2,3)
			console.log("result="+result)   //6

-----------
Define a function to judge whether a number is even. If yes, it returns true; otherwise, it returns false
              

                function isOu(num){
                    return num%2==0
                }
                var result = isOu(12)
                console.log(result)


Define a function that can calculate the area of a circle according to the radius and return the calculation result

                  function mianji(r){
                    return 3.14*r*r;
                }
                result = mianji(10);
                console.log(result)

--------
The argument can be any data type or an object. When we have too many parameters, we can encapsulate the parameters into an object and pass them through the object
--
Create a function that can output personal information on the console
You can output name, age, gender address
--

function sayHello(name, age, gender, address) {
				console.log("I am" + name + "I this year" + age + "Years old" + "I am a" + gender + "people" + "I live in" + address)
			}

// Say hello ("pig Bajie", 5, "male", "Gao Laozhuang") I'm pig Bajie. I'm five years old. I'm a man. I live in Gao Laozhuang
// Say hello ("pig Bajie", "male", 5, "gaolaozhuang") I'm pig Bajie. I'm male this year. I'm a five person person. I live in gaolaozhuang
=====In this way, the position of the formal parameter and the actual parameter must be consistent. Who is the first formal parameter and who is the first actual parameter? Otherwise, the above situation may occur when printed

So we need to create an object. The position in the object is reversed at will, and the printed result will be the result we want
function sayHello(o) {
				console.log("I am" + o.name + "I this year" + o.age + "Years old" + "I am a" + o.gender + "people" + "I live in" + o.address)
			}
			// Create an object
			var obj = {
				name: 'Sun WuKong',
				age: 3,
				gender: 'male',
				address: 'Gao Laozhuang'
			}
			sayHello(obj)

An argument can be an object or a function
mianji()
Call function
It is equivalent to using the return value of the function

            function mianji(r) {
				return 3.14 * r * r;
			}
			result = mianji(10);
			console.log(result)


			function funny(a){
				console.log(a)
			}
			 funny(mianji(5))
			//funny(mianji)

 mianji
Function object
It is equivalent to using function objects directly

            function mianji(r) {
				return 3.14 * r * r;
			}
			result = mianji(10);
			console.log(result)


			function funny(a){
				console.log(a)
			}
			// funny(mianji(5))
			funny(mianji)

 

---
Return the type of return value
The return value can be any data type, an object or a function
            

                function fun5(){
                    return 10;
                }
                var a = fun5()
                console.log(a)


----------------                
              

                 function fun5(){
                    var obj = {name: "Come on, wow"}; 
                    return obj;
                }
                var a = fun5()
                console.log(a)
             function fun() {
				alert("The function is about to execute")
				for (var i = 0; i < 5; i++) {
					if (i == 2) {
						// Use break to exit the current cycle (two pop ups output 0 1)
						// break;
						// Use continue to skip this cycle (two pop-up outputs 0 1 3 4)
						// continue
						// Use return to end the whole function (only the first pop-up box outputs 0 and 1)
						return;
					}
					console.log(i)
				}
				alert("The function is finished")
			}
			fun()
            function fun6(){
				// Declare another function inside the function
				function fun7(){
					alert('I am fun7')
				}
				fun7()
				// Return fun7 function object as return value
				return fun7;
			}
			// console.log(fun6())
			
			a = fun6();
			console.log(a)
			// a()
			// fun6()()

Execute function now

After the function is defined, it is called immediately. This function is called immediate execution function. The immediate execution function often executes only once

            (function(){
				console.log("I am an anonymous function")
			})();
			

			(function(a,b){
				console.log(a)
				console.log(b)
			})(123,12)

The property value of an object can be any data type or a function
          

            var obj = new Object()
            obj.name = "Zhang San"
            obj.sayName = function(){
                console.log(obj.name)
            }
 Adjustment method:
    obj.sayName() //---Zhang San
 Modulation function:
    fun()

A function can also be an attribute of an object. If a function is saved as an attribute of an object, then we call this function the method of the object. Calling this function means calling the method of the object, but it is only a distinction in name, and there is no other difference
          

Enumerate properties in objects:

            // Use for In statement
            // Syntax:
            for(var variable in object){
                
            }


            for... If there are several attributes in the in statement object, the loop body will execute several times. Each time, the name of an attribute in the object will be assigned to the variable
          

            var obj = {
                name:"Zhang San",
                age:18,
                gender:"male",
                address:"California"
            }

            for(var n in obj){
                console.log('hello')
            }   //hello output four times
 for(var n in obj){
                console.log('n')//---Attribute name age gender address
                console.log(obj[n])//---Attribute value Zhang San 18 male
                
            }   

Scope:

Scope refers to the scope of a variable
There are two scopes in JS: global scope and function scope

1. Global scope

--The JS code written directly in the script tag is in the global scope
--Global scopes are created when the page is open and destroyed when the page is closed
--There is a global object window in the global scope, which represents a browser window. It is created by the browser and can be used directly
--In the global scope, the created variables will be saved as the properties of the window object, and the created functions will be saved as the methods of the window object

                    function fun(){
					console.log("Hello")
					}
					// Hello
					window.fun() //Hello
					var a = 10
					console.log(window.a) //10
					console.log(window)

Declaration of variables in advance
Variables declared with var keyword will be declared (but will not be assigned) before all code execution,
Variables are not declared in advance if var keyword is not used
                      

                        console.log(a)
                        var a =123     -undefined


                        console.log(a)
                         a =123        //--Error reporting

Declaration of function in advance
-- function created in the form of function declaration function name () {}
Will be created before all code is executed, so we can call the function before the function declaration
-- functions created by function expressions are not declared ahead of schedule, so they cannot be called before declarations.
Function declaration,

                        // fun()
                        function fun(){
                        console.log("hhh")
                        }
                        fun()

                         //Before and after invocation, you can output hhh


                        var fun2 = function(){
                        console.log("wuwu")
                        }
                        fun2() //Can only be called later

All variables in the global scope are global variables, which can be accessed in any part of the page

2. Function scope

--The function scope is created when calling the function. After the function is executed, the function scope is destroyed,
Each time a function is called, a new function scope will be created, which are independent of each other
Variables in the global scope can be accessed in the function scope, but variables in the function scope cannot be accessed in the global scope b,
When operating a variable in the scope of a function, it will first look for it in its scope and use it directly if necessary. If you don't, go to the upper scope until you find the global scope,
If there is no global scope, an error ReferenceError is reported
To access global variables in a function, you can use the window object
In the function scope, there is also the feature of declaration in advance,
Variables declared with the var keyword will be declared before all the code in the function is executed,
Function declarations are also executed before all code in the function is executed

Not used in functions var Declared variables become global variables
					var a = 10
					function fun(){
						console.log(a)
						var b = 20
					}
					fun() //10
					console.log(b) //undefined 
					
					function fun3(){
						console.log(a) //undefined
						var a = 35
						fun4();
						function fun4(){
							console.log("I am fun4")
						}
					}  
					fun3() //I'm fun4 function
					
					
					var c = 20
					function fun6(){
						console.log(c) //undefined
						var c = 10
						c = 10  //(the global variable is equivalent to var C = 20 and VaR C = 10)
						d = 100 //(global variable without keyword)
					}
					
					fun6() //undefined
					console.log(c) //20
					console.log(d) //100
					
					-----
					var e = 222
					function fun7(){
						console.log(e)
					}
					fun7() //222
					
					var e = 222
					function fun7(e){
						console.log(e)
					}
					fun7(20)   //20
					//Defining formal parameters is equivalent to declaring variables in the function scope
					var e = 222
					function fun7(e){
						console.log(e)
					}
					fun7() --undefined
					
					var a = 123
					function fun(a){
						a=456
                        alert(a)
						
					}
					fun() //456
					alert(a)	//123	

					var a = 123
					function fun(a) {
						alert(a)
						a = 456
				
					}
			        fun() //undefined
			        alert(a) //123
			// Given the formal parameter a, then a = 456 is the local variable
			// If no formal parameter is given, then a = 456 is the changed global variable
			// fun()123
			// alert(a)456					

this:
              
When calling a function, the parser will pass an implicit parameter into the function every time
This implicit parameter is this. This refers to an object, which we call the context object of function execution,
this will point to different objects depending on the calling method of the function
                    1. When called as a function, this is always window fun()
                    2. Call in the form of a method. this is the object that calls the method
                  

                     function fun8(a){
                        console.log(a)
                        console.log(this)
                    }
                    fun8(23);  

Use the factory method to create objects, which can create objects in large quantities

function createPerson(){
			//Create a new object
			var obj = new Object()
			//Add attributes to objects
			obj.name = "Sun WuKong",
			obj.age = 18,
			obj.gender = "male",
			obj.sayName = function(){
				alert(this.name)
			}
			//Return the new object
			return obj;
		}

For objects created using factory methods, the constructor used is object
So all the objects created are of type Object,
As a result, we can't distinguish many different types of objects

function createPerson(name,age,gender) {
				//Create a new object
				var obj = new Object()
				//Add attributes to objects
				obj.name = name,
					obj.age = age,
					obj.gender = gender,
				obj.sayName = function() {
					alert(this.name)
				}
				//Return the new object
				return obj;
			}
			var obj2 = createPerson("Pig does not quit",16,"male")
			obj2.sayName()
			console.log(obj2)

Constructor
      

        var obj = new Person()
        var obj = new Cat()

Create a constructor, which is specially used to create the Person object. The constructor is an ordinary function. The creation method is no different from that of ordinary functions,
The difference is that constructors are used to capitalize the first letter
        
The difference between constructors and ordinary functions is the way they are called,
Ordinary functions are called directly, while constructors need to use the new keyword to call
        
Execution process of constructor:
        1. Create a new object immediately
        2. Set the newly created object as this in the function. You can use this in the constructor to reference the newly created object
        3. Execute the code in the function line by line
        4. Returns the newly created object as a return value

An object created with the same constructor is called a class object, and a constructor is also called a class,
The object we will create through a constructor is called an instance of the class
     

   function Person(){
            this.name = name
        }
        var per = new Person("Sun WuKong")
        console.log(per.name)


        
Use instanceof to check whether an object is an instance of a class
Syntax:
Object instanceof constructor, if yes, return true
      

        console.log(per instanceof Person)  //true
        console.log(per instanceof Object)  //true

All objects are descendants of Object,
Therefore, any Object and Object will return true when checking instanceof

          

this situation:
            1. When called as a function, this is window
            2. When called in the form of a method, this is who calls the method
            3. When called as a constructor, this is the newly created object

Modification of constructor
Create a Person constructor
- in the Person constructor, a sayName method is added for each object,
At present, our method is created inside the constructor,
That is, every time the constructor executes, a new sayName method will be created,
That is, the sayName of all instances is unique,
As a result, the constructor will create a new method once it is executed, and 10000 methods will be created 10000 times...
All the methods are the same, which is totally unnecessary. We can let them share one method and turn it into a global one

                function createPerson(name,age,gender) {
				//Create a new object
				var obj = new Object()
				//Add attributes to objects
				obj.name = name,
					obj.age = age,
					obj.gender = gender,
				obj.sayName = function() {
					alert(this.name)
				}
				//Return the new object
				return obj;
			}
			var obj2 = createPerson("Pig does not quit",16,"male")
			obj2.sayName()
			console.log(obj2)
            function Person(name,age){
				this.name = name,
				this.age = age
				this.sayName = fun

			}
			//Define the sayName method in the global scope

However, defining functions in the global scope pollutes the namespace of the global scope, and it is not safe to define functions in the global scope, so there are the following prototype objects

Prototype object:

prototype
For each function we create, our parser will add an attribute prototype to the function,
This attribute corresponds to an object, which is what we call the prototype object
If a function is called as an ordinary function, prototype has no effect. When the function is called in the form of constructor, there will be an implicit attribute in the object she creates,
To point to the prototype object of the constructor, we can__ proto__ To access this property
            
The prototype object is equivalent to a public area. All instances of the same class can access the prototype object
We can uniformly set the common contents of the object into the prototype object
When we access a property or method of an object, it will first look for it in the object itself. If there is one, it will be used directly. If there is no one, it will look for it in the prototype object. If it is found, it will be used directly
            
In the future, when we create constructors, we can uniformly add the properties and methods shared by these objects to the prototype object of constructors, so that we don't need to add them for each object separately,
Without affecting the global scope, each object can have these properties and methods
            function Person(){
                
            }
Add attribute a to the prototype of Person
          

 Person.prototype.a = 123


Adding methods to the prototype of Person
          

  Person.prototype.sayName = function(){
                alert('hello')
            }
            var per = new Person()
            var per1 = new Person()

            // console.log(Person.prototype)
            console.log(mc.a)
            console.log(per.__proto__ ==Person.prototype)
            console.log(per1.__proto__ ==Person.prototype)


The prototype object is also an object, so he also has a prototype,
When we use the properties or methods of an object, we will first look for them in ourselves,
If there is something in the prototype, you can use it directly. If there is nothing in the prototype, you can find it in the prototype,
Until the prototype of the Object object is found, the prototype of the Object object has no prototype. If it is still not found in the Object, it returns undefined

Garbage collection (GC):
Garbage will also be generated during the running of the program. After accumulating too much garbage, the running speed of the program will be too slow,
Therefore, we need a garbage collection mechanism to deal with the garbage generated during the operation of the program
        
When an object does not have any variables or attributes to reference it, we will not be able to operate the object. This object is garbage,
Too many such objects will occupy a lot of memory space, causing the program to run slowly,
So this kind of garbage must be cleaned up
There is an automatic garbage collection mechanism in JS, which will automatically destroy these garbage objects from memory,
We don't need or can't do garbage collection,
All we need to do is set the objects that are no longer used to null

Array


Built in object
Host object
Custom objects (most flexible and troublesome)
        
Array
Array is also an object. It has similar functions to our ordinary objects and is also used to store some values
The difference is that ordinary objects use strings as attribute names, while arrays use arrays as indexes to manipulate elements
Index: the integer starting from 0 is the index
The storage performance of array is better than that of ordinary objects. In development, we often use array to store some data
/ / add elements to the array
Syntax: array [index] = value
/ / read the elements in the array
If you read a nonexistent index, no error will be reported and undefiend will be returned
Syntax: array [index]
        console.log(arr[2])
/ / get the length of the array (number of elements)
For continuous arrays, use length to get the length of the array
For non contiguous arrays, using length will get the maximum index of the array + 1
Try not to create discontinuous arrays
Syntax: array length

 console.log(arr.length)


/ / modify the length
If the modified length is greater than the original length, the extra part will be empty. If the modified length is less than the original length, the extra element will be deleted
/ / add an element to the last position of the array
Syntax: array [array. length] = value
      

        var arr = [1,2,3]
        arr[arr.length] = 7
        console.log(arr)  //1,2,3,7


        
Array literal
Use literals to create arrays
Syntax: []
        var arr = [];
        console.log(arr)
When you use literals to create an array, you can specify the elements in the array at creation time
            

            var arr = [10,23];
            // console.log(typeof arr)
            console.log(arr)


/ / when using the constructor to create an array, you can also add elements at the same time. Pass the elements to be added as the parameters of the constructor. The elements are separated by
            
            

        var arr3 = new Array(10,222)
            console.log(arr3)


            
      

     //Create an array with only one element 10
            arr[10]
            //Means to create an array with a length of ten
            arr2 = new Array(10)
            console.log(arr2.length) ----10


            
The elements in the array can be any data type, object, function or array
          

 arr = ["hello",1,true,null,undefined] 
                var obj = {
                name:'Sun WuKong'
            }
            arr[arr.length] = obj
            
            arr = [function(){alert(1)},function(){alert(1)}]
            // console.log(arr)
            arr[0]()
            
            
            arr[[1,2,3],[3,4,5]]  ---Two dimensional array
            console.log(arr[0])


            
Four methods of array
            1.push() adds one or more new elements to the end of the array and returns the new length
         

            var arr = ["Sun WuKong","Zhu Bajie","Sand monk"]
            arr.push("Tang Monk")
            console.log(arr) ['Sun WuKong', 'Zhu Bajie', 'Sand monk', 'Tang Monk']
            
            var result =  arr.push("Tang Monk")
            console.log("result=" +result) ---4 New length


            2.pop()
Deletes the last element of the array and returns it.
          

             var arr = ["Sun WuKong","Zhu Bajie","Sand monk"]
            arr.pop()
            console.log(arr)  --Monkey King pig Bajie
            
            var result =  arr.pop()
            console.log("result=" +result) ---Delete who returns who


            3.unshift() adds a new element to the beginning of the array and returns a new length
After inserting the element to the front, the indexes of other elements will be adjusted in turn
            

            var arr = ["Sun WuKong","Zhu Bajie","Sand monk"]
          
            arr.unshift("How do you do")
            console.log(arr)
            ['How do you do', 'Sun WuKong', 'Zhu Bajie', 'Sand monk']
            var result =  arr.unshift("How do you do")
            console.log("result=" +result) ---4


            
            4.shift() deletes the first element of the array and returns it.
          

 var arr = ["Sun WuKong", "Zhu Bajie", "Sand monk"]
            var result = arr.shift()
            console.log(arr)
            console.log("result=" + result)  Sun WuKong


--- traversal of array
/ / traversal is to take out all the elements in the array

     var arr2 = ["Sun WuKong", "Zhu Bajie", "Sand monk"]
            for(var i = 0;i<arr2.length;i++){
                console.log(arr2[i])
            } //Monkey King pig Bajie sand monk

----Practice
            ----
Generally, we use the for loop to traverse an array, and JS also provides us with a method to traverse numbers
forEach() -- only browsers above ie8 are supported, and this method is not supported by browsers below ie8,
Therefore, if you need to be compatible with ie8, do not use forEach, or use the for loop to traverse
forEach() requires a function as an argument
Functions like this, which are created by us but not called by us, are called callback functions

var arr = ["Sun WuKong","Sand monk"]
			
			arr.forEach(function(){
			    console.log("Hello")
			})

//Hello (output twice)

//Several parameters will be output several times

var arr = ["Sun WuKong","Sand monk"]
			
			arr.forEach(function(a){
			   console.log("a="+a)
			})

//a = Monkey King
//a = sand monk    


If there are several elements in the array, the function will be executed several times. Each time, the browser will pass the traversed elements in the form of arguments
We can define formal parameters to read these elements
The browser passes three parameters in the callback function
The first parameter is the element currently being traversed
The second parameter is the index of the element currently being traversed
The third parameter is the array being traversed
            

var arr2 = ["Sun WuKong", "Zhu Bajie", "Sand monk"]
            arr2.forEach(function(value,index,obj){
                // console.log(value)
                // console.log(index)
                console.log(arr2== obj)
            })
//true

slice  
slice() selects a part of the array and returns a new array.
It can be used to extract specified elements from the array. This method does not change the element array, but encapsulates the intercepted elements into a new array
If the second parameter is not written, all elements from the beginning of the index will be intercepted
An index can pass a negative value. If a negative value is passed, it is calculated from back to front, - 1 represents the last element
Syntax: objects slice(start,end) subscript

 var arr2 = ["Sun WuKong", "Zhu Bajie", "Sand monk"]
            console.log(arr2.slice(0,2)) //Front closing and rear opening 
//Monkey King, pig Bajie


splice() adds / removes elements from the array.
Use will affect the original array, delete the specified elements from the original array, and return the deleted elements as return values
Parameters:
First: start position index
Second: indicates the number of deleted items
The third and later can pass some new elements, which will be automatically inserted in front of the start position index
          

 var arr2 = ["Sun WuKong", "Zhu Bajie", "Sand monk"]
            console.log(arr2.splice(0,2)) //Monkey King, pig Bajie
            console.log(arr2) //Sand monk


  
         (2) 

          

var arr2 = ["Sun WuKong", "Zhu Bajie", "Sand monk"]
			console.log(arr2.splice(0,1,"hhh"))
			console.log(arr2)

Array de duplication
			var arr = [1,2,3,2,1,3,4,2,5];
			for(var i = 0;i<arr.length;i++){
				// console.log(arr[i])
				for(var j = i+1;j<arr.length;j++){
					// console.log("later = = = =" + arr[j])
					if(arr[i] == arr[j]){
						arr.splice(j,1);
						// console.log(arr[i])
						j--
					}
				}
				console.log(arr[i])
			}

concat() concatenates two or more arrays and returns a copy of the connected array. This method will not affect the original array
join() concatenates all elements of the array into 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. This string will become the connector of the elements in the array. If it is not specified, it will be separated by default. If you don't want to use anything, you can directly pass an empty string join ("")
            
reverse() reverses the order of the elements in the array. This method will affect the original array
sort() sorts the elements of the array, which will also affect the original array. By default, it is sorted according to unicode encoding
Even for arrays of pure numbers, sorting with sort() will be based on unicode encoding, so you may get wrong results when sorting numbers
We can specify the sorting rules ourselves
We can add a callback function in sort() to specify the sorting rules
Two formal parameters a and b need to be defined in the callback function
The callback elements in the browser array will be used as the callback elements respectively
It is uncertain which element to call, but it is certain that array a must be in front of b
The browser will determine the order of elements according to the return value of the callback function
If a value greater than 0 is returned, the element swaps positions
If a value less than 0 is returned, the element position remains unchanged
If 0 is returned, the two elements are considered equal and the element position remains unchanged
          

  arr = [5,4]
             arr.sort(function(a,b){
                //Big in front
                if(a>b){
                    return 1
                }else if(a<b){
                    return -1
                }else{
                    return 0
                }
                
                //Ascending arrangement
                return a-b
                //Descending order
                return b-a
             })


             
          

  var arr = [1,4,3]
            var arr2 = [4,5,6]
            var arr3 = ["hahah","Winning streak"]
            console.log(arr.concat(arr2)) [1,4,3,4,5,6]
            console.log(arr.concat(arr2,arr3,"Respect your opponent"))  [1, 4, 3, 4, 5, 6, 'hahah', 'Winning streak', 'Respect your opponent']
            console.log(arr.join()) 1,4,3
            console.log(typeof arr.join()) string
            console.log(arr2.join("hello")) 4hello5hello6
            console.log(arr.reverse())3,4,1
            console.log(arr) 3,4,1
            console.log(arr.sort())1,3,4
            var arr = [1,11, 4, 3] 
            console.log(arr.sort()) [1, 11, 3, 4]


            
Function method
call() and apply()
Both methods are function object methods, which need to be called through function objects
When calling call() and apply() to a function, the function will be called to execute
            fun.call()
            fun.apply()
            fun()
Same effect
            
The difference is that when calling call and apply(), you can specify an object as the first parameter
At this point, this object will be called this when the function is executed
The call() method can call the arguments in turn after the object
            fun.call(obj,2,3)
The apply() method needs to encapsulate the arguments into an array and pass them uniformly
          

 fun.apply(obj,[2,3])
            function fun(){
                alert(this)
            }
            var obj = {}
            fun() ---window
            fun.call(obj)
            fun.apply(obj) object


            
this case 2
            1. When called as a function, this is always window fun()
            2. Call in the form of a method. this is the object that calls the method
            3. When called as a constructor, this is the newly created object
            4. When using call and apply calls, this is the specified object
    ===============        
arguments parameter list argument
When calling a function, the browser passes two implicit parameters each time,
            1. The context object of this function
            2. Object arguments encapsulating arguments
            
arguments is an array like object, not an array,
It can also manipulate data through index and obtain length
When calling the function, the arguments we pass will be encapsulated in arguments
            console.log(arguments instanceof Array) false
            console.log(Array.isArray(arguments)) false
            arguments.length can be used to get the length of the argument
Even if we do not define formal parameters, we can use them through arguments, which is just troublesome
arguments[0] first argument
arguments[1] second argument
Parameters are saved in arguments
      
The callee attribute corresponds to a function object, which is the object of the currently executing function
            console.log(arguments.callee)

Date:

Use a Date object to represent a time
                var d = new Date();
                alert(d)
If you directly use the constructor to create a Date object, it will be encapsulated as the execution time of the current code
/ / to create a specified time, you need to pass a string representing the time in the constructor as a parameter
Date format: month / day / year / hour: minute: Second
                
              

                getDate()    //Returns the day of the month (from 1 to 31).
                getDay()    //Returns the day of the week (0-6). 0 means Sunday and 1 means Monday
                getFullYear()    //Returns the year.
                getMonth()    //Returns the month (from 0-11). 0 means January
                getTime()    //Gets the timestamp of the current date object
                //Timestamp: returns the number of milliseconds since midnight on January 1, 1970 and the specified date. 1s=1000ms
                //The bottom layer of the computer uses time stamps when saving time


              

                var d = new Date()
                var date  = d.getDate()
                console.log(date)


                
Get the current timestamp, which can be used to test the performance of code execution
                time = Date.now()
                

Math object:

Unlike other objects, Math is not a constructor
It belongs to a tool class without creating objects. It encapsulates the relevant attributes and methods of mathematical operations
abs(x) returns the absolute value of X.
                  

  console.log(Math.abs(-1))  1


ceil(x) returns x, rounded up to the nearest integer.
Decimal places are rounded up as long as they have a value

                     console.log(Math.ceil(1.1)) 2
                     console.log(Math.ceil(-1.5)) -1

  
floor(x) returns x, rounded down to the nearest integer.
The decimal part is rounded off

  console.log(Math.floor(1.9)) 1

    
round(x) rounds x to the nearest integer. rounding
                    

 console.log(Math.round(1.2)) 1

  
random() returns a random number between 0 and 1.

  console.log(Math.random()) 0.5591525264361912


                     
Generate random numbers from 0 to 10
Generate random numbers of 0-X
                     for(var i = 0;i<100;i++){
                    console.log(Math.round(Math.random()*X))
            }
Generate random numbers between 1-10
                    console.log(Math.round(Math.random()*9)+1)
                    
Generate a random number between X and y
                    console.log(Math.round(Math.random()*(Y-X))+X)
                    
Max (x, y, Z,..., n) returns the number with the highest value.
Min (x, y, Z,..., n) returns the number with the smallest value.
                  

                    console.log(Math.max(10,20)) 20
                    console.log(Math.min(10,20)) 10


                    
pow(x, y) returns the Y power of X.
                  

 console.log(Math.pow(2,3)) 8  2^3


sqrt(x) returns the square root of X.      

 console.log(Math.sqrt(9))  3 

Packaging
Basic data type
        String Number Null Undefined Boolean
Reference data type
        Object
        
We are provided with three wrapper classes in JS, through which we can convert our basic data type to
Object
        1.String()
You can convert a basic data type String to a String object
        2.Number()
You can convert a basic data type Number to a Number object
        3.Boolean() 
Boolean values of basic data types can be converted to Boolean objects
        
But note that in development, we will not use objects of basic data classes
If you use the object of basic data class, some non overdue results may be brought when making some comparisons~
            
          

  var num = new Number(3)
            console.log(num)
            console.log(typeof num)  object
        
            // Add an attribute to num
            num.hello = "Hello"
            console.log(num.hello)
            
            If var a = 3
            a.hello = "Hello"
            console.log(a.hello)  --undefined


            
Methods and attributes can only be added to objects, not basic data types
When we call properties and methods on the values of some basic data types,
The browser will temporarily use the wrapper class to convert it into an object, and then call the object's properties and methods
After calling, convert it to basic data type
                    ∴
                  

 var a = 123
                    a = a.toString()
                    console.log(a)
                    console.log(typeof a) stirng


                    
String method
At the bottom, the string is saved as a character array
                ["h","e","l","l","""""]
                
Length: the length of the string
                
                charAt()    
Returns the character at the specified position.
Gets the specified character according to the index
It has no effect on the original string
                var str = "hello JS"
                console.log(str.charAt(0)) h
                
charCodeAt() returns the Unicode encoding of the character at the specified position.
                var str = "hello JS"
                console.log(str.charCodeAt(0))  104
                
                String.fromCharCode() creates a string from the character encoding.
                var str = "hello JS"
                console.log(str.charCodeAt(0))
                console.log(String.fromCharCode(104))  h 
                
concat() connection string. The function is the same as + 1
                var str = "hello JS"
                console.log(str.concat("hello")) hello JS hello
            
indexOf() retrieves a string. Retrieves whether the string contains the specified content
If it contains the content, it returns the index value of the content for the first time. If it does not, it returns - 1,
You can specify the second parameter, which specifies where to start the search
                console.log(str.indexOf("h",4)) starts from the fourth position to find h - 1
                var str = "hello JS"
                console.log(str.indexOf("why") - 1
            
lastIndexOf() searches for strings from back to front.
You can specify the second parameter, which specifies where to start the search
                var str = "hello JS"
            console.log(str.lastIndexOf("l")) 3 returns the following
            console.log(str.indexOf("l"))  2
            console.log(str.lastIndexOf("l",3))
            
slice() extracts the fragment of the string and returns the extracted part in the new string.
It does not affect the original string and returns the intercepted content
            console.log(str.slice(1,2)) --- e front closed and rear open
            console.log(str.slice(1,-3)) ello
            
substring() extracts the character between two specified index numbers in the string.
Unlike slice(), it cannot accept negative values as parameters. If a negative number is written, it defaults to zero
It also automatically adjusts the position of the parameter (1,0) and the default (0,1)
            
substr() extracts the specified number of characters from the string from the starting index number.
            console.log(str.substr(3,2)) lo 
Parameters:
            1. Start indexing
            2. Intercept length
            
split() splits a string into an array of strings.
Parameters:
If a string is required as a parameter, the array will be split according to the string
If you pass an empty string as an argument, each character is split into an element in the array
                var str2 = "hello,JS"
            result = str2.split("l") disassemble according to l
            console.log(result)
            console.log(Array.isArray(result))
            console.log(result[0]) he
            console.log(result[1]) is empty
            console.log(result[2]) o,JS
            
Tolocalelovercase() converts the string to lowercase.
toLocaleUpperCase() converts the string to uppercase.
            var str2 = "hello,JS"
            console.log(str2.split())  ['hello,JS']
            console.log(str.substring(0,3)) hel closed before opening
            


Regular expression
            admin
            admin@qq.com
            
Regular expressions are used to define rules for some strings
The computer can check whether a string conforms to the rules according to the regular expression, or extract the content conforming to the rules from the string
                
/ / create regular expression object
Syntax:
var variable = new RegExp("regular expression", "matching pattern")
                
                
/ / regular expression method
                test()
This method can be used to check whether a string conforms to the rules of regular expressions
Use typeof to check the regular object, and object will be returned
var reg = new RegExp("a") this regular expression can be used to check whether the string contains a, which is strictly case sensitive
You can pass a matching pattern as the second argument in the constructor
i ignore case
g global matching mode
If yes, it returns true; otherwise, it returns false
                var reg = new RegExp("a")
                var str = "a"; true
                
                
                var reg = new RegExp("a","i");
                //  reg = /a/i
                console.log(typeof reg)
                console.log(reg)
                var str = "A"  true
                
                str = "abc" true
                str = "bc" false
                var result = reg.test(str)
                console.log(result)
                
Regular syntax:
Use literals to create regular expressions
Syntax: var variable = / regular expression / matching pattern
It's easier to create using literal values
Using constructors to create more flexible
                        
Create a regular expression to check whether there is a or b in a string
Use / a|b /;
                reg = /a|b/;
Create a regular expression to check whether there are letters in a string
Use / [a-z] / for any lowercase letter
/ [A-Z] / indicates any capital letter
/ [A-z] / any letter
Ignore case / [a-z]/i
The content in [] is also related to or
                reg = /[ab]/   === reg = /a|b/;
                
Check whether a string contains abc adc aec
Use / a[bde]c/
                
[^] except...
                
[^ AB] except ab
                
String and regular related methods
                
split() splits a string into an array of strings, which will be split even if no global match is specified
                var str = "1a2b3c4d5e6f"
                var result = str.split("c")
                console.log(result)            ['1a2b3', '4d5e6f']
                
Splits the string according to any letter
Method can pass a regular expression as a parameter, so that the method will split the string according to the regular expression
                var result = str.split(/[A-z]/)  [1,2,3,4,5,6]
                
search retrieves only one value (indexof) that matches the regular expression, and it is useless to set global matching
If it is found, the index that appears for the first time will be returned. If it is not found, it will return - 1
It can receive a regular expression as a parameter, and then retrieve the string according to the regular expression
                str = "abc,aec,adc"
                result = str.search("abc")
                console.log(result)       0
Retrieves whether there is abc or aec or adc in the string
                result = str.search(/a[bed]c/)
                console.log(result)    0
If it is found, the index that appears for the first time will be returned. If it is not found, it will return - 1
                
Match finds the match of one or more regular expressions, and extracts the qualified ones from the string according to the regular expression
By default, match will only find the first one that meets the requirements. We can set the regular expression as the global matching mode,
You can also set multiple matching patterns for regular expressions, and the order does not matter
match encapsulates the matched contents into an array and then returns
This will match everything
                var str = "1a2b3c4d5e6f7A"
                result = str.match(/[A-z]/)
                console.log(result)  a
                
                result = str.match(/[A-z]/g)
                console.log(result)  a b c d e f
result = str.match(/[A-z]/gi) is global and ignores case
                console.log(result)  a b c d e f A
                
                
                replace()
You can replace the specified content in the string with the new content
Parameters:
                1. The replaced content can receive a regular expression as a parameter
                2. New content
Only the first one will be replaced by default
                result = str.replace("a","k")
                console.log(result)            
                1k2b3c4d5e6f
                result = str.replace(/a/gi,"k")
                console.log(result)            
                 result = str.replace(/[a-z]/gi,"")
                console.log(result) 1 2 3 4 5 6

Regular expression syntax:
Create a regular expression to check whether a string contains aaa
                
Quantifier:
Through quantifiers, you can set the number of times a content appears
{n} happened n times
{m,n} occurs m to N times
{m,} appears more than m times
+ at least one equivalent {1,}
* 0 or more are equivalent to {0,}
                    ? Represents 0 or one equivalent to {0, 1}
Quantifier only works on the content before it
                 var reg = /a{5}/; 5 occurrences a
             console.log(reg.test("aaaaac")) //true
             
              var reg = /(ab){2}/;
             console.log(reg.test("aabb")) //true
             var reg = /ab{2}/;
             console.log(reg.test("abb")) //true
             
1-3 times
             reg = /ab{1,3}c/
             console.log(reg.test(abc)) true
             
Check whether a string starts with a
^ indicates the beginning
Check whether a string ends with a
$means the end
             reg = /^a/
             console.log(reg.test("abc")) true
             console.log(reg.test("bac")) false
             
              reg = /a$/
             console.log(reg.test("bca")) true
             console.log(reg.test("bac")) false
If both ^ and $are used in a regular expression, the string must fully conform to the regular expression
             reg = /^a$/  
             console.log(reg.test("a")) true
             console.log(reg.test("aca")) false
reg = /^a|a $/ starts or ends with a
              console.log(reg.test("aca")) true
              
Check whether a string contains
              . Represents any character
Use \ as an escape character in regular expressions
              \. express.
\ \ indicates\
Note: when using the constructor, because its parameter is a string and \ is the escape character in the string,
If you want to use \, you need to use \ \ instead
              var reg = /\./
              reg = new RegExp("\\.")
Finds a single character, except for line breaks and line terminations
               reg = /\./
               
               

\w    Find word characters. Any alphanumeric underline
\W    Find non word characters. and\w contrary
\d    Find a number.
\D    Find non numeric characters.
\s    Find white space characters.
\S    Find non white space characters.
\b    Match word boundaries.
\B    Matches non word boundaries.


Create a regular expression to check whether a string contains the word child

var reg = /\bchild\b/

console.log(reg.test("hello children")) //false
console.log(reg.test("hello child ren")) true


DOM

The interaction between the browser and the DOM is the behavior of the user,
For example, click the button and move the mouse to close the window
We can set some js codes in the properties corresponding to the event, so that when the event is triggered, these codes will be executed

Loading of documents
When the browser loads a page, it loads it from top to bottom, and runs one line after reading it
If the script tag is written on the top of the page, when the code is executed, the page has not been loaded, and the DOM object has not been loaded, which will cause us to be unable to obtain the DOM object
    
So we write js code to the bottom of the page so that we can execute js code after the page is loaded
    
The onload event is triggered after the entire page is loaded
Bind an onload event for window
The response function corresponding to this event will be executed after the page is loaded,
This ensures that all DOM objects have been loaded when our code is executed
  

  window.onload = function(){
        
    }
    


DOM query
The childNodes property will get all nodes, including text nodes. According to the DOM label, blank nodes will also be regarded as text nodes
Note: browsers in IE8 and below will not treat blank text as child nodes, so this attribute will return 4 child elements in IE8,
The other browsers are 9
    
The children attribute can get all the child elements of the current element
firstchild can get the first child node of the current element (including blank text)
firstElementChild does not support ie8 and below browsers. If they need to be compatible, they should try not to use them
    
innerText this property can get the text content inside the element
It is similar to innerHTML, except that it automatically removes html tags


    

 

 

 

DOM operation

JSON

Allowed values in json:

String, numeric, Boolean, null, object, array

//Create a json object
var arr = '{"name":"Sun WuKong","age":18,"gender":"male"}';
var arr = '[1,2,3,"hello",true]'


                  


              
         

Topics: Javascript Front-end html