js Basics

I want to tidy up some js basics that I reviewed myself, and I hope it will help you.

What is JavaScript?

  • JavaScript: A scripting language that runs on the browser client based on object and event drivers. [js]

  • js engine: execute js code

  • Rendering Engine: Kernel

✔ The running environment of js: a language running on the browser side ✔ Finally, all JS code is executed as an object, and execution is triggered by events [DOM]

JavaScript is a scripting language and a lightweight programming language.

Scripts in HTML must be between <script>and </script>tags.

Write js code between <script>and </script>tags

JavaScript has a variety of data types: numbers, strings, arrays, objects, and so on

Writing position:

<body>
    <!-- Writing position -->
    <!-- Embedded -->

    <script>
        // js code
    </script>

    <!-- Outer Chain -->
    <!-- Note: Don't write any other code inside the outer chain label -->

    <script src="./js/test.js"></script>

    <!-- Inline -->
    <!-- css   -->
    <!-- <div class="box" style="color: red;"></div> -->
    <div class="box" onclick="alert(666);"></div>
</body>

Output statement:

<body>
    <!-- Output Statement -->

    <script>

        // Document Output
        // document.write("I am <br>in a sentence");


        //  Common & Important Console Output
        // console.log("The weather is good today");
        // console.error("Ouch, something went wrong");
        // console.info("I am an info");
        // console.warn("I warn you, stay away from me!");


        // A pop-up box with a confirmation button
        // alert("I'm a pop-up box");

        // Boxes with confirm and Cancel buttons
        // confirm("I can confirm and cancel");

        // Pop-up box with confirm cancel and input box

        // prompt("I can type, haha");
    </script>
</body>

Variables:

variable

Variable: A variable is a container variable that holds data in a program. It is the identifier of the data stored in the computer's memory. The data stored in memory can be obtained by the name of the variable. In short, it is used to store data.

 Define Variables
 		var  Variable name;
 assignment
 		Variable Name = value;
    var Variable Name = data;
 Summary:
	 1. A variable can only hold one value at a time
     2. Last assignment result
     3. Variables are case sensitive ( js Case sensitive)

Naming rules:

 A word that must be observed or not observed. JS Engine Discovery and Error

1. By letter(A-Za-z),number(0-9),Underline(_),Dollar Sign( $ )Compositions such as: var usrAge, num01, _name
2. Case sensitive emphasis: JS Strictly case sensitive, var app; and var App; Are two variables
3. You cannot start with a number or define a variable name in Chinese characters
4. It cannot be keywords, reserved words, and code symbols, for example: var,for,while,&, class
5. No spaces are allowed
6.Variable names must make sense
7. Follow the hump nomenclature. The first letter is lowercase, and the first letter of the following words needs to be capitalized.

Data type:

Data type: Data type refers to the data type of a variable

Data types are divided into: simple data types, complex data types

Simple data type [number, string, boolean, null, undefined]
Number:

 All numbers belong to this type [integer, decimal, negative]

☞ As long as the value of a variable is a specific number, the data type of the current variable is the numeric type

☞ number Number size represented by type:
	  Maximum is±1.7976931348623157 308 power multiplied by 10     Number.MAX_VALUE
	  The minimum value is±5 Multiplied by 10-324 Power								  	Number.MIN_VALUE

☞ Numeric type representation: (Understanding)

	 ✔ Decimal representation
   
		var  n1=10,n2=9,n3=100;

	 ✔ Hexadecimal representation
   
		With 0 x Numbers between the first 0 and 9, a(A)-f(F)Between the letters. a-f The corresponding number is 10-15
		[0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f]

		var num = 0xA;

	 ✔ Octal representation
   
		Octal starts directly with the number 0, with 0-7 The number composition between.[0,1,2,3,4,5,6,7]
  	var num1 = 07;   
  	var num2 = 06;  
  	var num3 = 05;   

☞ Remarks:
	 When performing arithmetic calculations, both octal and hexadecimal values are ultimately converted to decimal values.

String type:

The string can be any text in quotation marks. Single or double quotation marks may be used
	If the data is letters, symbols, Chinese characters, these are all string types, string types are quoted
☞ stay js Single quotation marks are recommended for variables of general string type in.
	Alphabets, Chinese characters, and symbols must be enclosed in quotation marks if they exist as data. var num = "abcdefgabcd""aaaaaaaaa";]

  Whatever data is included in quotation marks becomes a string type

	1,Letters, Chinese characters, symbols
	2,Quote any character type
	3,Strings and strings cannot be written directly next to each other

☞ Be careful:
	 1. Nesting between single and double quotation marks
			For example:Output    I am"Tall, handsome and rich"code monkey;  
  
   2. Escape Character [\]
	 \n      Line Break
   \\		   Slash
   \'		   Single quotation mark
	 \"		   Double Quotes
	 \r 	   carriage return
  For example:
  var strMsg = 'I'm the GOD of my world ~!';   //Output: I'm the GOD of my world ~!
  var strMsg2 = "I"m the GOD of my world ~!";  //Output: I"m the GOD of my world ~!
  var strMsg3 = 'The backslash is this \\,Magical!';  //Output: The backslash is this\, amazing!
  • Boolean type
     true(True) and false (False)
    There are only two results (only two states), all represented by Boolean values

  • null empty type, undefined type (understand)

    //If a variable is not assigned, the default is undefined
    var n1;
    //If the value of a variable is undefined, the data type of the variable is undefined.

    Complex data types

  • Object type [Everything is an object]

  • Array array

Expressions and Statements

Expression

An expression can produce a value, possibly an operation, a function call, or a literal quantity. Expressions can be placed anywhere they need a value.

Sentence

Statements can be understood as an action, and loop and judgment statements are typical statements. A program consists of many statements, in general; Split a statement one by one

Data Type Judgment

Use  typeof Variables give the data type of the corresponding variable
 ☞ For example:
	   var n1 = 123;
		//Get n1 data type
		console.log(typeof n1);
		var n2 = '123';
		console.log(typeof n2);
		var n3 = true;
		console.log(typeof n3);

Determine if a variable is a number

NaN:not a number [special value] is NaN:is not a number [judgment]

Used to determine if a value is a number, false if it is a number, true if it is not

isNaN(n): 'aaa' is not a number

isNaN: ==>is not a number

isNaN(n) ==> n is not a number

isNaN(x) Method
	==>x Is a number{false}
	==>x Not a number{true}
is not a number
isNaN(n)==>3 is not a number

For example:
	var usrAge = 21;
  var isOk = isNaN(usrAge);
  console.log(isNum); // false, 21 is not a non-numeric value

  var usrName = "James";
  console.log(isNaN(usrName));//true, "James" is a non-numeric value

Data Type Conversion

Convert to numeric type [Number, parseInt, parseFloat]

 Number(variable): 
  	 Summary:
     	  1. This method allows you to convert a data type to a numeric type
        2. In the process of conversion, the original value can be retained, encounter decimal directly retained, will not be discarded
        3. If a variable cannot be converted to a numeric type, the result returned is NaN; The corresponding data type is still a numeric class
        4. If you convert a Boolean type to a numeric type, true The result after conversion is 1  false The result after conversion is 0
   
        NaN: not a number[number Type]
          
  ☞ parseInt(variable)	Rounding
  
  	var num1 = parseInt("12.3abc");  // Returns 12, if the first character is a number it parses until it encounters a non-numeric end
    var num2 = parseInt("abc123");   // Returns NaN if the first character is not a number or symbol
    Remarks:
        1  Only the integer part is preserved, and the result of data type conversion is an integer
        2. If a value in a variable cannot be converted to a specific number, the result returned is a NaN Value of
        3. NaN (not  a  number)   ----NaN The corresponding data type is a numeric type
        4. This method allows you to convert other data types to numeric types
        
  ☞ parseFloat(variable)	Take floating point
		Summary:
    	 1. This method allows you to convert other data types to numeric types
         2. During the conversion process, if a decimal is encountered, the decimal portion is preserved directly
         3. Return results if conversion is unsuccessful NaN
    

Transstring type [n.toString, String(n)]

variable.toString()
 		var num = 5;
		console.log(num.toString());

☞  String(variable)

n.toString();
String(n)
Remarks:
		String()Significance of a function: Some values do not toString(),You can use it at this time String(). 
		For example: undefined and null

Turn Boolean(n)

Boolean(n) 
 Remarks:
	 0  |''(Empty String) | null | undefined | NaN  Will be converted to false  Everything else will be converted to true

operator

Arithmetic operator

operation
	Summary:
     1. If you add variables of numeric type, the result is a result of numeric type
     2. If a variable of type string is added together, the result is a string (the plus sign serves to stitch strings)
   If+A number on either side is a mathematical addition, and a string connection is performed if a string appears on both sides
 - operation
	 Summary:
     1. If a variable of numeric type subtracts, the result is a result of numeric type
     2. If the strings of numbers are subtracted, the result is also a numeric type result (implicit type conversion occurs)
            var n1 = '123';
            var n2 = '123';
     3. If non-numeric strings are subtracted, the result is NaN
 * operation
	 multiplication
	
 / operation
	   1.If a variable of numeric type is divided, the result is a result of numeric type
     2. If the strings of numbers are divided, the result is also a numeric type result (implicit type conversion occurs)
     3. If a non-numeric string is divided, the result is NaN
     4. If the divisor is 0, the result is Infinity (Infinite value)
	 
 %Remainder (Get Remainder) [Find Remainder by Dividing Two Numbers]  

Assignment Operators

+= |  -=   |  *=  |  /=  |   %=   |   = 

var  a += b ;    =====> Equivalent to        a = a+b;
compound assignment operators

Grammar:
	a += 3;// a = a + 3
	b += 9;// b = b + 9

Unary operator

1. ++(Self-increasing)  and  --(Decrease by itself)

 2. ++ operation
 	 	++a       In variables a Add 1 to the base
    a++	   In variables a Add 1 to the base

    ✔ If the a++ perhaps ++a When assigned to a variable, the value of that variable differs
    
       ◆ If the a++ Assign a variable, then first add a The original value is assigned to the new variable, then added to 1 by itself (assignment before calculation)
       ◆ If the ++a Assign a variable, then add 1 first, and assign the calculated result to the new variable
       
  var n = 2;
	var m = n++;//Assignment followed by self-addition
	var m = ++n;//Add before assign

Comparison operator

1.   >  		greater than
    
2.   <			less than
    
3.   >=     Greater than or equal to, as long as one is satisfied
    
4.   <=     Less than or equal to, as long as one is satisfied

5.  ==      Used only to compare whether values in variables are equal, regardless of data type
    
6.  ===     Values and data types must be equal at the same time [all equal, constant equal, absolute equal]
    
7.  !=	    Determine whether values are not equal, regardless of data type
 
8.  !==     Judgement value and data type
 
    
☞ Summary:
	  ✔ There are only two results from the comparison operator, one is correct and the other is wrong.
    ✔ The result from the comparison operator is only true[Correct] and false[error]

Logical operators

1. ||  Or: a condition can only be met if one is met
 		true || true ==>There is one for true,Is in place true,Only two are false,Only then false
    Summary:
      	1. If one of the conditions is a knot true(Representatives have a condition met),Then the final result after the pass or operation is true
        2. If none of the results in the condition is satisfied, the result after passing or operation is false
     
 2. &&  And: Require that all conditions must be met before you can
 		true && true==>true,Otherwise it is false
 	  Summary:
	      1. If the conditions are all true ( true),Then the final result is true after passing and calculating ( true)
        2. If at least one of the conditions is not satisfied ( false),Then pass and the result is false
        
    Students in blue down clothes or red trousers went out
          
 3. ! Not (Reverse) : Boolean conversion:!!'123'
	
		If it rains tomorrow, we'll play basketball

Operator Priority

1,When more than one operator participates in an operation, you must be aware that there is a priority problem with these operators
2,Parentheses first, assignment operator last

Priority from high to low
	1. ()  Highest priority   
	2. Unary operator  ++   --   !
	3. Arithmetic operator first*  /  %   after +   -
	4. Relational Operators  >   >=   <   <=
	5. Equality Operator  ==    !=     ===    !==
	6. Logical Operator First &&   after ||
	7. Assignment Operators
  
When more than one operator participates in an operator, it must be consciously aware that the operator has priority, and the assignment operator is last executed

Test:
	var num = 10;
  var sum = num++ + ++num + num;
	var sum = num++ + num + ++num;
  console.log(sum);//?
  console.log(num);//?

Assignment Operator, Arithmetic Operator, Comparison Operator, Logical Operator

array

Array: You can save more than one data at a time, and an array is also a container for storing data.

Create Array

Constructor creates array

Literal Create Array

var  Custom Array Name = [] ;

Array assignment

Create an array and assign values

☞ Literal assignment
 	 var  ary = [1,2,3,4,6];

Assignment by Index

var  ary = [];
ary[0]=1;
ary[1]=2;

Because arrays are a whole, we want to get one of the values in them by using subscripts (index values)
Array:[20,22,36,19,26,18]
Subscript:[0, 1, 2, 3, 4, 5]
Value: Array[subscript]
Assignment: Array[subscript] = Value;
Minimum Subscript: 0, Maximum Subscript: Array.length - 1
 Summary:
  	1. Index values in arrays start at 0
    2. Assign values to arrays by index, set in order of number
    3. By array name.length You can get the length of the current array

Get the value in the array

Gets the values in the array indexed from 0

☞  Grammar:
	    Array name[Index number]

	 For example:
	   var  ary = [1,2,3,4,5];
	   ary[0];
	   ary[1];

Multidimensional Array

var arr = [
	[1,2,3],
	[4,5,6],
	[7,8,9]
];
First line:1[0][0],2[0][1],3[0][2]
Line 2: 4[1][0],5[1][1],6[1][2]
Line 3: 7[2][0],8[2][1],9[2][2]

Process Control

Sequential structure, Branch structure, Loop structure

Conditional Judgment (Branch)

if statement

  • Single branch: if (conditional judgment) {statement block}: conditional judgment (true) ==>statement block, [if false, do not execute statement block]

  • Two branches: if (conditional judgment) {statement block}else{statement block}==>condition (true)==>statement block after if, as long as condition (false) executes else statement block

  • Multiple branches: if (conditional judgment) {statement block} else if (conditional judgment) {statement block} else if (conditional judgment) {statement block}... Else{statement block}

grammar

if (conditional judgment) {statement block}

//Single conditional expression
if(n){Statement block}//n will be converted to boolean type
   if ( Conditional expression [result of Boolean type] ) { 
   	    Logic code.
    }else {
        Logic code.
    } 

//Multi-conditional expression
if ( Conditional expression ) {
    
}else if ( Conditional expression ) {
    
}......else {
        
}

1. Single Conditional Assessment Code Execution:
* ✔ Judge the result of the expression first
* ✔ If the result is true, the program will only execute statements in if, not else
* ✔ If the result is false, the program will only execute statements in else, not if

Ternary operations

grammar

Similar: if () {} else {}

Format: Expression? Result 1: Result 2;

Scenarios using ternary operations: ternary operators can replace simple conditional judgments

Execution process

✔ First determine if the result of the expression is true or false ✔ If the result is true, then code execution result 1 ✔ If the result is false, then code execution result 2

?===> Equivalent to if:=====>in conditional judgment equivalent to else

switch Statements

Note: When switch ing between variables and values after case, it uses three equals (all equals)

grammar

switch ( variable ) {
    case  Value 1:
        Code Statement..
    	break;
    case  Value 2:
        Code Statement...
   		break;
   	.......
    default:   
        Code Statement...
   		break;
}

Summary: 1. If you want to represent a range in your program, conditional judgment is recommended

2. If a specific value is represented in the program, a switch statement can be used

Note: the switch judgment and so on are all judgements

  1. The variable data type after switch must be one to the value data type after case

  2. The break statement must be added

Differentiation: if switch is used for fixed value judgment, if if is used for range judgment

Loop variable initialization [var i = 1]

Judgment of Circulation Conditions [i <= 100]

Changes in Circulating Variables [i = i + 1; i +;]

Circulation: repeat one more event

Execute loop code when condition is met
Loop code is not executed when the condition is not satisfied

Three elements: variable initialization, cycle condition judgment, cycle variable change

while Loop

Purpose: To execute a piece of code repeatedly with a loop

while(Conditional expression) {
    Code (loop)
}

//Loop variable initialization: (define a variable to initialize a value) var n = 1;
//The judgment of the cycle condition: (as the judgment of whether the cycle continues) n <= 100;
//Variables of cyclic variables: (Let the variable change so that the loop is not executed indefinitely) n = n + 1;
var i = 1;
while ( i <= 100 ) {
	// Loop body [a bunch of code]
    document.write('Li Xunguan');
	i++;
}
Execution:
Loop variable initialization==>Conditional judgment ( true)==>Circulatory body(i++)==>Conditional judgment ( true)==>Circulatory body(i++)==>Conditional judgment ( false)==>Break
  1. Prerequisite judgment whether the structure is true or false

  2. If true, the program will always execute the code in the loop

  3. If the condition is false, the program immediately jumps out of the loop body code and finishes execution

Do.. While loop

do {
    Loop body code
}while(Conditional expression)
Circulatory body==>Conditional judgment ( true)==>Circulatory body==>Conditional Judgment(true)==>Circulatory body==>Conditional Judgment(false)==>Break

Execute the loop body code first, then judge the condition If the condition is true, continue executing the loop body code If the condition is false, the loop body code immediately ends and jumps out of the loop

The difference from a while loop:

1. If the condition is not satisfied, the do while loop will execute one more time than the do while loop

2. If the condition is satisfied, the do while loop and the do while loop execute the same number of times.

for loop

grammar

For (var I = 1; I <= 100; i+) {//circulator}

If you can specify the number of loops, it is recommended to use for Loop, if the number of loops is uncertain, you can use while Obtain do while loop
for (Variable Initialization; Conditional expression ;  Variable increasing (variable decreasing)) {
     Loop body code
}

for(Variable Initialization;Conditional Judgment;Variable Change){//Cyclic body}

initialize variable==>Conditional Judgment(true)==>Circulatory body==>Variable Change==>Conditional judgment ( true)==>Circulatory body==>Variable Change==>Conditional judgment ( false)==>Break

continue Statement

Characteristic

When a program encounters a continue, it will end the cycle and the code that follows will not execute. Go into the next cycle.

break statement

Characteristic

When a program encounters a break statement, the program terminates immediately, and subsequent code does not execute

The execution process of the loop

For loop: for (var I = 1; I < n; i+) {loop body}

If the number of loops is uncertain: while, do, while,

Number of loops determined:for

break and continue

break: jump out of the whole cycle, continue: jump out of the current cycle to continue the next cycle

Bubble sort

Sort: Ordered arrangement [from small to large, from large to small]

Bubble sort:

1. Confirm how many times an array can be swapped to get results [Length-1]

2. How many comparisons per trip [length-number of trips]

3. Compare the previous number with the latter number of arrays. If the previous number is greater than the latter number, switch the positions

// Sort analysis process
       // Number of comparisons in the first 5 times = Array length - Number of trips
       // Number of comparisons on second, fourth, second = array length - number of trips
       // 3 trips 3 trips 3 comparisons = array length - number of trips
       // Number of comparisons in 4th, 2nd, 4th = Array length - Number of trips
       // Number of comparisons in the 5th trip, 1st trip, 5th trip = Array length - Number of trips
       // Number of Passes + Number of Passes = Array Length

        // Analysis conclusion:
        // 1. Number of trips: Array length - 1
        //2. Number of comparisons per time = Array length-Number of trips
        //3. If the front is bigger than the back, change the position each time.

      
        // Number of comparisons: To compare the results, compare the length of the array to -1 before the final result appears
        //Number of comparisons per time = Array length - Number of trips
        // If the front is larger than the back, swap locations

        var arr = [56, 89, 99, 75, 97, 88];
        // 1. Determine how many trips to compare to produce results
        // 2. Determine the number of comparisons per trip
        // 3. Comparison between two
        for(var i = 1; i <= arr.length - 1; i++) {//i represents the number of trips

            //frequency
            for(var j = 0; j < arr.length - i; j++) {//j represents number of times
                // Use j as array subscript
                // compare
                if(arr[j] > arr[j + 1]){ //If the front is larger than the back
                    //exchange
                    var t = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = t;
                }
            }
       }
       document.write('The final sorting result is:'+ arr);

function

Why learn functions?

Function: A specific piece of function code can be encapsulated and then called by the function name to reuse the function: Encapsulation of a piece of (function) code

Function focus: encapsulation, repetition

Create function

Create: function function function name () {}

Call: function name ();

Mode 1: Function declaration and execution (recommended)

Declarations of functions:

function  Custom function name() {
     //A bunch of code
    Specific function code
    A bunch of code==>Function Body
     //Function Body
}

Be careful:
	 1. Since a function is used to implement a specific function code, we usually start with a verb when we set the function name.
     2. Functions cannot execute code on their own, they need to be called by the function name to execute the code

Call Function (Execute Function)

Function name();  //Calls to functions

Mode 2: Function expression (literal quantity) and execution

var  fn = function () {

}   
fn();

Parameters of the function

Formal parameters

Variables defined in the small extension when a function is created

Grammar:

Formal parameter: placeholder, no real data per se
function Function name(Formal parameters,Formal parameters,Formal parameters...) {//A formal parameter is a placeholder with the same naming rules and specifications as variables
	//Function Body
}
Be careful:
	  1 Functions can also be passed as parameters

Arguments

Argument, the actual data passed in in the small extension when the function is called.

Grammar:
Arguments: real data
 Function name(data,data,data...);   //An argument is the actual data

return value of function

Think: How do I get the sum of any two numbers calculated by the code above outside the function?

Note: Values inside a function cannot be taken directly outside the function

Return value: After the function is executed, the result of execution can be returned to the caller through return syntax

Purpose: To return a value outside a function;

function add(num1,num2){
		//Function Body
		return num1 + num2; // Note: The return ed code does not execute
}
var resNum = add(21,6); // Call the function, pass in two arguments, and receive the function through resNum to return the value
alert(resNum);// 27

Note: [Important!!!!]
    1. If the function is not used as shown return Statement, then the function has a default return value: undefined
    2. If the function has been written return Statement followed by nothing else, then the return value of the function is still undefined
    3. A function can only have one return value
    4. return When code execution is complete, subsequent code is no longer executed
    5. Functions can also be used as return values (understand)

Other parts of the function

Use of arguments

arguments object

Number of function parameters obtained from arguments [how many parameters exactly are indeterminate functions]

Summary: 1. If the parameters of the function are uncertain, you can define the function without writing the parameters and get them by arguments
2. If the parameters of the function are determined, it is recommended that the parameters be written when defining the function

Anonymous and self-calling functions

Anonymous function: A function without a function name

var  fn = function () {
    
}

Summary:

1. Anonymous functions cannot be used alone
2. Anonymous functions can be assigned to a variable
3. Allow anonymous functions to call themselves

Self-calling function: function encapsulated and executed immediately

1. Self-calling functions can be either named or anonymous
    2. ( function () {} )(); 

Function is a data type

Functions can be used as parameters

Functions can be return values

Function Scope and Local Variables

Scope

Think about whether a variable defined inside a function can be accessed outside the function

Scope: The area in which a variable or function can function

_Global Scope (Global Variable)

  1. Variables defined in script tags or js files can be accessed anywhere

  2. Declaring variables within a function does not use the var keyword (not recommended)

_Local scope (local variable)

  1. Variables defined within a function

  2. Local variables can only be used in functions that define variables

_Block-level Scope

{Block Scope}

1. Variables in a block-level scope are essentially inaccessible externally
2. However, variables with block-level scope can be accessed in js (proving that js has no block-level scope)

Global Scope (Global Variable)

Declare variables outside all functions and use them everywhere


	var age = 18;  
  console.log(age); 

  function fn(){
     console.log(age)
  }

  fn();

Local scope (local variable)

A variable or a function's parameter declared inside a function and can only be used inside a function

function fn(a){
   a = 100;
   var b = 200;  
}
	  
fn();
console.log(a); 
console.log(b);

Scope Chain

Scope chain: When a variable is accessed, it is first searched from the scope, if it is not found, it is searched from the upper scope, and so on, a scope chain is formed.

	var a = 1;
    function fn1(){
      var a = 2;
      function fn2(){
          console.log(a);   //Value of a 
      }
      fn2();
    }
    fn1();

Pre-parse

Pre-parse:
	1. js Code Execution Performs Pre-parsing First
    2.  Promote variables first: Promote variable declarations to the top of the current scope, excluding variable assignments
    3. Function Promotion: Promotes the function declaration to the top of the current scope, excluding function calls
    
  [Pre-parsing: Variables and Functions)
  [Have var Variable of the current scope, refer to the definition syntax of the variable, refer to the top (note: only define no assignment)
  [Named function, elevates the definition syntax of this function to the top of the current scope (Note: Define only without calling)  

object

A specific transaction [a specific instance in a class] [a collection of properties and methods]

Literal Create Object

var variable name = {key: value, key: value, key: functon () {}};

var o = {
    name: 'zs',
    age: 18,
    sex: true,
    sayHi: function () {
    		console.log(this.name);
    }
}; 

Create Objects from Objects

Constructor, a special function (method) used with new to initialize (create) objects

var  variable  =  new Object()
 1. Object Is a constructor
 2. adopt new Call Constructor

Add properties: object variables. Property name = value;

Add method: Object variable. Method name= function () {}

Factory-style object creation

function  create ( name, age, height ) {
var  Ob = new Object()
	  Ob.name = name;
	  Ob.age = age;
	  Ob.height = height;
	  Ob.eat = function () {}

return Ob;
}

Custom Constructor Create Object

function  CreateHero ( name, age, height ) {
		this.name = name;
		this.age = age;
		this.height = height;
}

Introduction to instanceof keyword

Object name instanceof constructor name

Determine which constructor created the object

Traversing Objects

Traverse the member for (key in object) {object [key]} of an object via for in

Traversing attributes in objects

Traversing through values in objects

Assign one variable to another, pass

Value transfer: Copy one copy of the data and pass it to another variable [Two copies of data] [Simple data]

Reference Pass: Copy a copy of the data address for transfer [One Data] [Complex Data]

Simple data types (value types) are stored on a stack of memory

Complex data types (reference types) are stored on the heap in memory

Built-in Objects

Math Object

Math.PI) Get the circumference [property]

Math.random() returns random numbers greater than or equal to 0 but less than 1 [flexible]

Math.max() Returns the maximum value in a set of numbers

Math.min() Returns the minimum value in a set of numbers

The formula of random number for two numbers:
  Math.floor( Math.random() * (m - n + 1) + n );
Math. Floor (Math.random() * (large-decimal + 1) + decimal);

There are many more to list.

Date object

Date Formatting Method
	var d = new Date();
    d.toString();  //Convert to String
    d.toDateString();  //Convert to date string
    d.toTimeString();  //Convert to Time String
    d.toLocaleDateString();   //Returns the local date format (different browsers have different effects)
    d.toLocaleTimeString();   //Return to local time format (different browsers have different effects)

Get the rest of the date(master)
	d.getSeconds()  //Get seconds
    d.getMinutes()  //Get Minutes
    d.getHours()    //Get Hours
    d.getDay()      //Return to the day of the week (0 means Sunday)
    d.getDate()     //Return to the day of the current month
    d.getMonth()    //Return month (from 0)
    d.getFullYear()  //Return year

Array array object

Common methods in arrays

Determine if a variable is an array    Array.isArray(ary)  

toString()   								// Convert an array to a string, separated by commas
 valueOf()   								//  Returns the array object itself

 ary.pop() [Common]    				 //Returns the last word in the array, and changes the length of the array
 ary.shift()  							  //Modify the length of the array by removing the first element from the array

 ary.push() [Common]  					 // This method has a return value that represents the latest length of the array, and it can set multiple parameters
 ary.unshift(number)   			//Add a value at the beginning of the array


☞ Summary of other methods
reverse()  									// Flip Array
 concat()  									//Stitch two arrays together to return a new array
 slice(startindex, endindex)   //Intercept a new array from the current array 
	✔ The first parameter indicates the starting index position,The second parameter represents the end index position
splice(startindex, deletCont, options)  //Delete or replace some values in the array
	✔ The first parameter represents where to start deleting
  ✔ The second parameter represents a total of several deletions
  ✔ The third parameter represents the value to be replaced
 indexOf(content[,index]),lastIndexof()   //No Return-1 lookup found
  ✔ Find a value in an array,If the return index location is found,If no return is found-1
  ✔ lastIndexof()  Start at the end of the array,If found,Return index position,If no return is found-1
 join()   	//Link each element of an array together by one character
	sort()		// sort

String string

Attributes: length,length
 Character method
 	 1. charAt(index)  		//Gets the character at the specified location
	 2. str[index]		   //Get the character at the specified position (method in H5)

String Method
 	 1. concat()   //Split String Equivalent to+
   2. slice(strat,end)       //From the specified position, intercept the string to the end position, the end value is not reached
   3. substring(start,end)   //From the specified position, intercept the string to the end position, the end value is not reached
   4. substr(start,length)   //Truncate length length by one character starting at the specified location

Location Method
   1. indexOf(character)   //Returns the position of a character in a string [first time]
	 2. lastIndexOf(character)  //Look backwards and forwards, only for the first matching character [last time]

 Remove blanks
  	trim()      //Only white space before and after strings can be removed

Case Conversion
  	toLocaleUpperCase()  //Convert to uppercase
    toLocaleLowerCase()  //Convert to lowercase

 Other
  	replace(a,b)  // Replace a with b
	  split()   //	Split a string into an array with a splitter

API and webAPI

Document Tree

Document Tree: When a browser loads an html file, it converts the document, the tags, attributes, text, and comments in the document into objects, and stores them in memory in a tree structure according to the relationship between tags (father-son, brother, grandchild).

Objects in the document tree, also known as node objects.

Classification of node objects: document s, elements (objects labeled), text, attributes, comments

  • API (Application Programming Interface) Application Programming==Interface== (Exposed Tools).

  • webAPI: Open interface of browser platform to operate browser and web page (BOM, DOM)

  • DOM: How to manipulate page elements

  • BOM: Operates the browser's

  • Introduction to DOM

    Concepts of DOM

    Concept: Document object model.

  • Document: html file

  • Object: Properties and Methods

  • Model: (Tree)

What do you want to do with learning DOM

Operating on page elements

Get, register events, actions

  • Get Elements [DOM Provider Method]

  • Register events for elements

  • Attributes of operation elements

  • Dynamic operation elements (create, append, delete, clone, etc.)

Get Elements

Get a single element based on the id value

  • document.getElementById('id value');

  • Get a set of elements by tag name

  • Syntax: document.getElementsByTagName('Tag Name');

  • Getting a single element from a selector

  • Syntax: document.querySelector('selector');

Get a set of elements from a selector

Event Base

What is an event

What users do is events

Interaction between users and Web pages (mouse click, mouse entry, mouse departure, keyboard press, keyboard pop-up, finger press, finger movement, etc.)

Event Three Elements

  • Event source: The triggered element, such as the button clicked

  • Event type: How to trigger an event, such as clicking the button onclick

  • Event handler: The result of an event.

Event Delegation

Event Delegation (Event Agent): Registers the events of the descendant element and gives them to the parent element agent of the descendant element entirely. Note: Delegates are subordinate elements that delegate superior elements. No superior delegates subordinate

How to implement event delegation

  • Implementation Steps

    (1) Register events with superiors of descendant elements

    (2) In the event handler, pass==event object. target==Get the first triggered element

    (3) Event objects can be passed by == target's nodeName==property detects whether the first trigger is a specified element

<script>
// (1) Register events with superiors of descendant elements
var ul = document.querySelector('ul');
ul.onclick = function(e) {
 // (2) In the event handler, pass through the event object. target gets the first triggered element
 var t = e.target;
 // console.dir(t);
 // (3) through the event object. The target's nodeName property detects whether the first trigger is a specified element
 if(t.nodeName=='LI') {
   console.log(t.innerText);
 }
};
</script>

 

Principle of event delegation

  • Key: Event objects. target; You can get the first triggered element

  • Principle: Because event bubbles exist, we can get the element that triggers first. [Goal_document]

offset series properties of elements

Get the size of an element

  • Elements. offsetWidth/element. offsetHeight;

    The number returned. Size includes: Content + padding + border;

    Note: This property is only readable and cannot be set

Get the position of the element

  • Elements. offsetLeft / element. offsetTop;

    The number returned. (Refer to who? See positioning relationships)

Gets the parent element of an element

  • Elements. offsetParent and element. Differences between parentNode

  • Elements. offsetParent, get the parent element, and follow the positioning relationship.

    • Elements. parentNode, get the parent element, according to the label relationship.

Element's client series properties

1.1 Get the size of the element

  • Elements. clientWidth/element. clientHeight

    Gets the size of the element, including Content + padding

Get the thickness of the border

  • Elements. clientLeft / element. clientTop

Element's scroll series properties

Get the size of an element

  • Elements. scrollWidth/element. scrollHeight

    The size of the element obtained, including Content + padding + Overflow

    Get Rolled Page Spacing

  • Elements. scrollLeft / element. scrollTop

    Gets the spacing of pages rolled up in this element. [This property is not only available, it can also be set]


     

Keywords: Javascript Front-end Vue.js

Added by zampu on Fri, 11 Feb 2022 21:00:01 +0200