js Basics (continuously updated)

Introduction to javascript

Structure: html
Performance: css
Behavior: Javascript = > JS weakly typed language

    js First acquaintance
    avaScript Is a client script language designed for interaction with web pages

    JS form:
        ECMAScript  Basic grammar   ECMAScript5 => ES5   => ES6
        BOM    (Browser Object Model)  Browser object model interface and method for operating browser  (Page jump forward and backward to identify the device type)
        DOM    (Document Object Model)  Document object model    Provides interfaces and methods for operating documents  => Get element action element

Basic data type of JS

JS data type = > describes various types of data

7 Data types
string  number  boolean    null   undefined   array    object
 String number    Boolean value      Null value                array     object

antic: character string=>Black number/Boolean value=>blue  null/undefined => grey  

How to distinguish data types ?
typeof data  => data type(A string is returned)

null         => "object"
undefined   => "undefined"\

Math related methods

Math (object) related methods (tools to complete specific functions)

 Math.random()   Randomly generate a 0-1 Random number of    =>  [0,1)
var num = Math.random();   // First assign a random number of 0-1 to the variable num
console.log(num);


var num = Math.random() * 100;   // [0,1) * 100 => [0,100)
console.log(num);

 Process decimal      ceil   floor   round
 Math.ceil()  You can receive a parameter and round it up to return => Enter 1 if there are decimal places
var num1 =  Math.ceil(num);
console.log(num1);

 Math.floor()  You can receive a parameter, round it down and return   => Remove decimal places
var num2 = Math.floor(num);
console.log(num2);

 Math.round() You can receive a parameter and return it after rounding it   => rounding
var num3 = Math.round(num);
console.log(num3);

 Math.min()   You can receive one or more parameters(Comma separated),Returns the minimum value
var min = Math.min(2,8,4,6,5,7,9,3,1);
console.log(min);

 Math.max()   You can receive one or more parameters(Comma separated),Returns the maximum value
var max = Math.max(2,8,4,6,5,7,9,3,1);
console.log(max);

 Math.abs()   You can receive a parameter and return the absolute value of the number
var a = Math.abs(10);
var a = Math.abs(-10);
console.log(a);

 Math.pow(m,n)   Two parameters can be received  => m of n Power
var b = Math.pow(2,10);
console.log(b);

 Math.PI         returnπ 
console.log(Math.PI);

Cast type

string number boolean null undefined

Number()   Pass in a parameter,Convert it to a number and return it  (Convert other types to numbers)

 var result = Number("100");
 console.log(result);

console.log(Number("100"));  // 100
console.log(Number("100a"));  // NaN

console.log(Number(100));  // 100

console.log(Number(true));  // 1
console.log(Number(false));  // 0
console.log(Number(null));  // 0
console.log(Number(undefined));  // NaN */


 String()  Pass in a parameter,Converts it to a string and returns  (Convert other types to strings)

console.log(String("100"));  //  "100"
console.log(String("100a"));  //  "100a"

console.log(String(100));  // "100"

console.log(String(true));  // "true"
console.log(String(false));  // "false"

console.log(String(null));  //  "null"
console.log(String(undefined));  //  "undefined"

Cast type_ Boolean

string number boolean null undefined

 Boolean()  Pass in a parameter,Converts it to a Boolean value and returns  (Convert other types to Boolean values)

 "" 0 NaN null undefined  => Convert to Boolean false  

console.log(Boolean("100"));  //  true
 console.log(Boolean("100a"));  //  true
 console.log(Boolean("a"));    //  true
 console.log(Boolean(" "));   // Space string true
 console.log(Boolean(""));    // Empty string false
 console.log(Boolean(100));  // true
 console.log(Boolean(-100));  //  true
 console.log(Boolean(0.5));  //  true
 console.log(Boolean(0));  //   false
 console.log(Boolean(NaN));  //   false
 console.log(Boolean(Infinity));  //   true

 console.log(Boolean(true));  // true
 console.log(Boolean(false));  // false

 console.log(Boolean(null));  //  false
 console.log(Boolean(undefined));  //  false

parseInt and parseFloat

parseInt() parseFloat() is mainly used to handle numbers and strings. Other types = > Nan

 parseInt()   Convert other types to integers(integer)    1.To unit 2.Round down
 law: Find the number before the first non number and convert it to an integer 
 parseFloat()  Convert other types to floating point(You can keep decimals)
law: Find the number before the first non number and keep the decimal 

 var width = "200px"; // => 200
var width = "2a00px"; // => 2
var width = "a200px"; // => NaN

var width = 200.55;   // => 200
var result = parseInt(width);
console.log(result); 
var width = "200px"; // => 200
var width = "200.55px"; // => 200.55
var width = "2a00.55px"; // => 2
var width = 200.55; // => 200.55
var result = parseFloat(width);
console.log(result);

The difference between a + + and + + A

a++ ++a itself increases in terms of results

If there are other operations during auto increment
 a++  Assign first and then increase automatically
 ++a  Self increment before assignment

var a = 10;
a++;
console.log(a);

var a = 10;
++a;
console.log(a);


 If there are other operations during auto increment
 a++  Assign first and then increase automatically
 ++a  Self increment before assignment

var a = 10;
var n = a++;     // var n = a; a = a + 1;    Assign first and then increase automatically
console.log(n);  // 10
console.log(a); // 11

var a = 10;
var n = ++a;    // a = a + 1;   var n = a;    Self increment before assignment
console.log(n);  // 11
console.log(a);// 11

Select structure

Select the structure and execute the corresponding code according to different situations

 Select structure   if  

 Single branch
 Double branch
 Multi branch

Only when a single branch meets the conditions can it be executed. Otherwise, no operation will be performed
 if(expression){
     Execute statement;
 }
 If the expression holds(true),Then execute{}Statements in(Execute statement),Otherwise, do nothing,Continue to execute the code after selecting the structure
 Double branch    Two options => We have to go one
if(expression){
     Execute statement 1;
 }else{
     Execute statement 2;
}
 Solve the expression if the expression holds(true),Then execute{}Execute statement 1 in ,Otherwise, execute else Corresponding{}Statement 2 in
 Judgment complete => Continue executing the statement after the selection structure
 Multi branch    
if(Expression 1){
    Execute statement 1;
}else if(Expression 2){
    Execute statement 2;
}else if(Expression 3){
    Execute statement 3;
}else{
    Execute statement 4;
} 

Implicit type conversion of relational operators

ASCII => GB2312 GBK => unicode => UTF-8

Implicit type conversion of relational operators   >  >=   <  <=   ==   !=
1.  character string,Boolean values are implicitly converted to numbers before being compared with numbers
2.  String and string comparison, Compare characters in order ASCII Code size
3.  null and undefined  encounter  >  >=   <  <=  Will turn the numbers first and then compare
                      encounter  ==   !=  Direct comparison without conversion (No comparability)
4.  null and undefined  Are numerically equal(==)
5.  NaN Is not equal to any value

++-- implicit type conversion for

++– implicit type conversion for
When other types of data (string boolean null undefined) encounter + + - it will be implicitly converted to numbers first, and then increase / decrease automatically

var a = 10;
var a = "10"; // "10" => 10   a++  => 11
var a = "10a"; // "10a" => NaN   a++  =>NaN
var a = "";    // "" => 0   a++  => 1

var a = true;    // true => 1   a++  => 2
var a = false;    // false => 0   a++  => 1

var a = null;    // null => 0   a++  => 1
var a = undefined; // undefined => NaN   a++  =>NaN

Operator precedence

Arithmetic operator    * / %   greater than   +  - 
Relational operator    > >=  <  <=  greater than  ==  !=   ===  !==  
Logical operator    !   &&   ||
Assignment Operators     ++ --     greater than    =  +=  -= *=  /=  

() . []  > !  ++  -- > Arithmetic operator  >  Relational operator  > Logical operator (!Relatively special)  > Assignment Operators  (++ -- Relatively special)

switch of selection structure

switch is a typical multi branch
switch(week){
case constant 1: execute statement 1; break;
case constant 2: execute statement 2; break;
case constant 3: execute statement 3; break;
case constant 4: execute statement 4; break;
case constant 5: execute statement 5; break;
default:
Execute statement 5;
break;
}

 switch The expression in is usually a variable/constant, List the possible situations of this variable;

 switch How to execute?
 switch Expressions and in case Constants in are congruent in turn(===) compare ,If congruent, the corresponding statement is executed, Statement execution completed, encountered break Will jump out switch structure; If not equal,Continue the downward comparison, If all are not satisfied, execute default Subsequent statements


 difference:
 switch It is more suitable for numerical judgment to list the possible situations of variables
 if     More suitable for range judgment, Multiple conditions

switch penetration of selection structure

switch is a typical multi branch
switch(week){
case constant 1: execute statement 1; break;
case constant 2: execute statement 2; break;
case constant 3: execute statement 3; break;
case constant 4: execute statement 4; break;
case constant 5: execute statement 5; break;
default:
Execute statement 5;
break;
}

 switch The expression in is usually a variable/constant, List the possible situations of this variable;

 switch How to execute?
 switch Expressions and in case Constants in are congruent in turn(===) compare ,If congruent, the corresponding statement is executed, Statement execution completed, encountered break Will jump out switch structure; If not equal,Continue the downward comparison, If all are not satisfied, execute default Subsequent statements

 break The function of is to jump out of the current switch structure,without break The statements of subsequent branches will continue to be executed,Without judgment


 difference:
 switch It is more suitable for numerical judgment to list the possible situations of variables
 if     More suitable for range judgment, Multiple conditions

switch penetration application of selection structure

switch is a typical multi branch
switch(week){
case constant 1: execute statement 1; break;
case constant 2: execute statement 2; break;
case constant 3: execute statement 3; break;
case constant 4: execute statement 4; break;
case constant 5: execute statement 5; break;
default:
Execute statement 5;
break;
}

 switch The expression in is usually a variable/constant, List the possible situations of this variable;

 switch How to execute?
 switch Expressions and in case Constants in are congruent in turn(===) compare ,If congruent, the corresponding statement is executed, Statement execution completed, encountered break Will jump out switch structure; If not equal,Continue the downward comparison, If all are not satisfied, execute default Subsequent statements


 switch pierce through
 break The function of is to jump out of the current switch structure,without break The statements of subsequent branches will continue to be executed,Without judgment
 utilize switch Penetration can be categorized by value

 difference:
 switch It is more suitable for numerical judgment to list the possible situations of variables
 if     More suitable for range judgment, Multiple conditions

ternary operator

Syntax:
Expression 1? Expression 2: expression 3;

First, solve expression 1. If expression 1 holds,Then solve expression 2, otherwise solve expression 3

while Loop

while syntax structure
while (expression){
Execute statements;
}

 First solve the expression ,If the expression holds(Meet the conditions),Then execute{}Circular statement in; Statement execution completed,Solve the expression again,If it still holds,Then continue the cycle,Otherwise, it will jump out of the loop and execute the statement after the loop

do while loop

while judge before execute = > rational
do... while whether the condition is true or not, execute it first and then judge = > Impulsive Type

 summary: 
 contrast while and do...while
 Generally prefer to use while
 Only in while Used when handling loop logic is awkward do...while

for loop

for syntax structure

for(i=0;i<length;i++){
    Execute statement;
}

Keywords in the loop

 continue;    Skip this time to the next  (It can only be used in loop statements to end this loop, that is, skip the following unexecuted statements in the loop body, and then proceed to the next loop)

be careful: 
(1) be located continute Subsequent statements are not executed
(2) about while and do-while Cycle, continue The action after statement execution is conditional judgment(Solving expression);about for Loop, followed by variable update(Self increasing/Self subtraction). 

break  Keywords of cycle 
break Used in a loop to jump out of the current loop 

be careful:
(1) be located break Subsequent loop statements are not executed
(2) If there are multiple nested loops,break Just jump one floor(Current cycle)

Function encapsulation process and function call

A function is to abstract a piece of code that completes a specific function and make it an independent entity in the program with a name (function name). It can be reused many times in the same program or other programs (called by function name).

Function encapsulation process
(1) First write the code to complete the specific function
(2) Put the code that completes a specific function into the function and give it a name
(3) Determines the return value of the function => The return value is determined by the user,If you don't set the default undefined
(4) Call function => Function name()
 About function calls
(1) Function before calling,Are stored in the browser's memory as text parameters (Function names can be understood as variable names),Only when called
(2) Each call to the function executes the context in the function
(3) Function encountered return The subsequent code is not executed

Nesting of functions

Function nesting means that one or more functions can be nested and called in one function
 be careful: 
When a function is nested => Only when the inner function is executed,The outer function will continue to execute backward  (Code execution process)
If the return value of the inner function is returned out of the outer function  => The outer function is also required return This value (About return value)

Recursion of function

recursion  
The function calls itself in the execution process.;

be careful: Recursion must have a jump condition

Dead recursion   => Similar to dead cycle
function fn(){
     console.log("This is fn function");
     fn();
 }
fn();

Tail recursion  =>   Get the final result at the end and pass it back in turn
    function fn(i,sum){ // fn(2,12)
    console.log(i,sum);
    sum += i;
    if(i == 1){
        return sum;
    }
    return fn(i-1,sum);  // fn(1,14)
    }
Dependency recursion  =>  The result of each function depends on the result of the previous one or more functions
    function fn(n){
    if(n == 1) {
        return 1;
    }
    return n + fn(n-1);
    }

JS precompiling

What process does the code in JS go through from loading to execution?

1. Syntax parsing 
Occurs before code execution script Is there a syntax error in the => Report an error if there is an error,Code not executed

2. precompile    =>   Occurs before code execution,Preparation before code execution
(1) global scope  => Preparation before code execution in global scope
a.  Variable promotion     Promote variable declaration to current script Front of  (be careful:Variables declared without keywords => Global variables have no variable promotion)
b.  Determine the function body and promote the whole function declaration of the named function to the current level script Front of 

(2) Function scope     Preparation before code execution in function
a.  Variable promotion     Promote the variable declaration to the front of the current function scope 
b.  Determine the function body and promote the named function to the front of the current function scope 
c.  Assign the actual parameter to the formal parameter  

3. Explain that the execution code is executed from top to bottom

Creation method of JS function

 one. Named function (Declarative)
function add(a,b){
    return a + b;
}
 console.log(add);
 add()

 By default  js Syntax is interpreted in the way of named functions when parsing functions  => Anonymous functions cannot be created directly and placed in the scope  (Anonymous functions generally cannot exist alone)
 function(a,b){
     return a + b;
 }

 two .Anonymous function
 1. Store anonymous functions in variable array objects   (Assignment formula)
 var fn = function(a,b){
     return a + b;
 }
 console.log(fn);
 var result = fn(1,2)
 console.log(result);

 var arr = [1,2,3,function(){}]
 var obj = {
     name:"Zhang San",
     age:18,
     say:function(){
         console.log("hello");
     }
 }

 btn.onclick = function(){
     alert(1111);
 }

 2. Self calling of anonymous functions/Self execution
 (function(a,b){
     return a + b;
 })

 ;+function(a,b){
         return a + b;
 }
 ;-function(a,b){
         return a + b;
 }
 ;!function(a,b){
         return a + b;
 }

How arrays are created

How arrays are created  
 1. Literal /Direct quantity creation  => Quick create
 var arr = [2,8,4,6,5,9,7,3,1];  
 var arr = [];      //Empty array
 console.log(arr);

 2. Constructor(Array)establish 
 var arr = new Array(2,8,4,6,5,9,7,3,1);  // new Array() calls the constructor 
 var arr = new Array();  //[]
 console.log(arr);
 
 Array properties:
 1. yes length attribute,Table length(Number of elements in the array)
 2. Maximum value of corresponding subscript value and assigned subscript = length - 1
 3. Can be iterated

Expansion method of array

Method of officially encapsulated operation array
 What should we pay attention to when learning the expansion method of array?
1. Remember the function of the method
2. Method
3. Whether to affect the original array  => (1. Some methods operate directly on the original array 2. Some methods get a new array from the original array)

Addition, deletion, modification and query of array
push() adds one or more elements to the end of the array
Return value: Length of array after adding elements
 Whether to affect the original array: influence

var arr = ["a","b","c"];
var result = arr.push(100);
var result = arr.push(100,200,300);
console.log(result);
console.log(arr);
unshift() adds one or more elements to the head of the array
Return value: Length of array after adding elements
 Whether to affect the original array: influence

var arr = ["a","b","c"];
var result = arr.unshift(100);
var result = arr.unshift(100,200,300);
console.log(result);
console.log(arr);
pop() deletes an element at the end of the array
Return value: Deleted element
 Whether to affect the original array: influence

var arr =  ["a","b","c","d"];
var result = arr.pop();
console.log(result);  // "d"
console.log(arr);     // ["a","b","c"]

var result = arr.pop();
console.log(result);  // "c"
console.log(arr);     // ["a","b"]
shift() deletes an element at the head of the array
Return value: Deleted element
 Whether to affect the original array: influence

var arr =  ["a","b","c","d"];
var result = arr.shift();
console.log(result);
console.log(arr);
splice() add, delete or modify anywhere
delete
splice(startIndex,n)    Subscript from startIndex Start deletion at n Elements
 Return value: A new array of deleted elements
 Whether to affect the original array : yes
var arr = [2,8,4,6,5,7,9,3,1];
var result = arr.splice(2,4);
console.log(result);
console.log(arr);

newly added
splice(startIndex,0,arg1,arg2...argN)    Subscript from startIndex Start deleting 0 elements at,Add one or more elements in the(New elements are added from the third parameter)
Return value: A new array of deleted elements  => Not deleted []
Whether to affect the original array : yes

var arr = [2,8,4,6,5,7,9,3,1];
var result = arr.splice(2,0,"a","b","c");
console.log(result);
console.log(arr);

modify
splice(startIndex,n,arg1,arg2...argN)    Subscript from startIndex Start deletion at n Elements,Add one or more elements in the(New elements are added from the third parameter)
Return value: A new array of deleted elements
 Whether to affect the original array : yes

var arr = [2,8,4,6,5,7,9,3,1];
var result = arr.splice(2,3,"a","b","c");
console.log(result);
console.log(arr);


Find determines whether an element exists in the array?   => Analog packaging
var arr = [2,8,4,6,5,7,4,9,3,1];  
console.log(arr);
includes() determines whether an element exists in the array (added in ES6)
Return value: existence:true non-existent:false
 Whether to affect the original array:  Not affect

var result = arr.includes(1);
var result = arr.includes("1");
console.log(result);
console.log(arr);
indexOf() returns the first occurrence of an element in an array
Return value: Returns the subscript if the element is present,Otherwise return-1
 Whether to affect the original array:  Not affect

var result = arr.indexOf(4);    // 2
var result = arr.indexOf("4");  // -1
console.log(result);
indexOf() can also be used to determine whether an element exists
existence index >= 0  index != -1 
non-existent  index == -1
reverse() flip / reverse of array
Return value: Flipped original array
 Whether to affect the original array: influence

var arr = ["a","b","c","d","e"];   // =>  ["e","d","c","b","a"]
var result = arr.reverse();
console.log(result);
console.log(arr);

slice(startIndex,endIndex)   Array clipping  [startIndex,endIndex) 
startIndex Starting subscript(Default value:0)
endIndex   Termination subscript(Default value:Length of array length)

Returns a new array of values after trimming
 Affect original number:Not affect

Commonly used in:
(1) Front end paging
(2) Copy the array to get a new array with the same elements as the original array

var arr = [1,2,3,4,5,6,7,8,9];

var brr = [];
for(var i=0;i<3;i++){
     var item = arr[i];
     brr.push(item);
 }
 var result = arr.slice(0,3);
 var result = arr.slice(3,6);
 var result = arr.slice(6,9);
 console.log(result);
 console.log(arr);


 var brr = [];
 for(var i=0;i<arr.length;i++){
     var item = arr[i];
     brr.push(item);
 }

Get a new array with the same elements as the original array
 var result = arr.slice();
 console.log(result);
 console.log(arr);
sort() sort of array
 Character sorting(default)  according to ascii Sequential sorting of code table   


 Return value:         Sorted original array
 Whether to affect the original array:  influence

 Character sorting
 
 var list = [52, 9,  28, "A", 3, 71, "a", 94, 1000000000, 62, 46, 5];
 var result = list.sort();
 console.log(result);
 console.log(list);

 Pure digital sorting
 
 sort() Pass in a function,There are two formal arguments in the function(a,b Two elements involved in the comparison),The function returns an arithmetic expression that specifies how to sort
 var list = [52, 9, 28, 3, 71, 94 ,62, 46, 5];
 list.sort(function(a,b){
    // console.log(a,b);
    // return a - b;  //  A - b > 0 = > a > b if the previous number is greater than the latter, exchange the positions of the two numbers (from small to large)
    return b - a;  // B - a > 0 = > a < B if the previous number is less than the latter, exchange the positions of the two numbers (from large to small)
});
console.log(list);
concat() splices multiple array elements to form a new array
 If it's an array,Then traverse the array and put each element in the new array
 If not an array,Then put it directly into the new array

 Return value:New array formed by splicing
 Whether to affect the original array: Not affect

 var arr = [1,2,3];
 var brr = [4,5,6];
 var crr = [7,8,9];

 var result = arr.concat(brr,crr);
 var result = brr.concat(arr,crr);
 console.log(result);
 console.log(arr,brr,crr);

 []
 var result = arr.concat("a",brr,"b",crr,"c");
 console.log(result);
 console.log(arr,brr,crr);

 Get a new array with the same elements as the original array
 var arr = [1,2,3];
 var list = arr.concat();
 console.log(list);
 console.log(arr);


 join(char)   Concatenate arrays into strings with specific characters (char default",")
 Return value:Concatenated string
 Whether to affect the original array: Not affect

 var list = ["a","b","c","d"];  // "abcd"
 var str = ""; 
 for(var i = 0; i< list.length;i++){
     var item = list[i]; // Every element in the array
     str += item;
 }
 console.log(str);


 var list = ["a","b","c","d"];  // "a-b-c-d"
 var str = ""; 
 for(var i = 0; i< list.length;i++){
     var item = list[i]; // Every element in the array
     if(i!= list.length-1){
         str += item + "-";
     }else{
         str += item ;
     }
 }
 console.log(str);

var list = ["a","b","c","d"];
var result = list.join("-");
console.log(result);
var result = list.join("+");
console.log(result);
var result = list.join("*");
console.log(result);
var result = list.join("");
console.log(result);
var result = list.join();
console.log(result);

for in and for of

 string number boolean null undefined  => Value type (Common data type)
 array  object    => Reference data type(Special data type)

 var arr = [4,8,2,6,5,7,9,3,1];
 var arr = new Array(4,8,2,6,5,7,9,3,1);
 
 Array properties
 length
 Subscript value and assignment      Maximum value of subscript = length - 1
 Can be iterated   
 0   length-1
 
 var arr = [4,8,2,6,5,,,,,,,,,,,7,9,3,1];
 console.log(arr);
 for(var i = 0;i<arr.length;i++){
     console.log(i,arr[i]);
 }

 for...in   Traversing the array returns the index of the array
 be careful:
 1. adopt for...in Subscript obtained by loop traversal index Is a string type 
 2. for...in Null values are skipped when looping through arrays(Spare time)

 var arr = [4,8,2,6,5,,,,,,,,,,,7,9,3,1];
 console.log(arr);
 for(var index in arr){
     console.log(index,typeof index,arr[index]);
 }

 for...of   Traversing the array returns the value of the array
 
 var arr = [4,8,2,6,5,7,9,3,1];
 console.log(arr);
 for(var val of arr){
    console.log(val,arr.indexOf(val));
}

object

Array can store multiple pieces of data, but the description of the data is not clear enough
var arr = ["Zhang San", 55, 66, 77];
console.log(arr,typeof arr);

 object: A description of the characteristics and behavior of a thing or class of things
 be careful
 (1) Object is based on key value(key:value)On the existence of form
 (2) Array is also a special object  (The key name is a number)
 (3) Key names are strings and quotation marks can be omitted

 How to create objects?   The quotation marks of key names can be omitted
 1. Literal creation
 var zhang = {
      Key name(Property name string) : Key value(Property value of any type)
     "name":"Zhang San",
     "chinese": 55,
     "math":66,
     "english":77,
     "hobby":["sing","dance"]
 }
var zhang = {}; // {} empty object
var zhang = {
    // Key name (property name string): key value (any type of property value)
    name:"Zhang San",
    chinese: 55,
    math:66,
    english:77,
    hobby:["sing","dance"]
}
console.log(zhang);

 2. Constructor creation(Object)
var zhang = new Object({}) // {}
var zhang = new Object({
    name:"Zhang San",
    chinese: 55,
    math:66,
    english:77,
    hobby:["sing","dance"]
});
console.log(zhang);

Properties of objects

Array can store multiple pieces of data, but the description of the data is not clear enough
var arr = ["Zhang San", 55, 66, 77];
console.log(arr,typeof arr);
console.log(arr.length,arr[0]);

 object: A description of the characteristics and behavior of a thing or class of things
 be careful
 (1) Object is based on key value(key:value)On the existence of form
 (2) Array is also a special object  (The key name is a number)
 (3) Key names are strings and quotation marks can be omitted

 Properties of objects:
 (1) Corresponding key name value and assignment  (Ranked in no order)
  a. Point grammar      object.Attribute name      => Quick value
  b. Bracket      object["Attribute name"]   => String is required in brackets/variable => Object traversal function encapsulates object value
 Object value cannot be obtained(Take a nonexistent property name) Then return undefined
 If the object assigns a non-existent attribute, the attribute will be added to the object

 (2) Can be iterated  for...in 

Shallow and deep copies of arrays

Shallow replication(Copy)   Two data references the same piece of memory space. As long as one changes, the other will also be affected(===)
 var arr = [1,2,3];
 var brr = arr;  // brr = [1,2,3]
 brr.push(4);    // brr = [1,2,3,4]
 console.log(arr,brr,arr === brr);
 
 Deep replication(Copy)  Get a new array that is the same as the original array element
 var arr = [1,2,3];
 
(1)  Create a new array, traverse the original array, and put each element in the new array
var brr = [];
for(var i = 0;i<arr.length;i++){
    var item = arr[i]; //1 2 3 
    brr.push(item);
}
console.log(arr,brr,arr === brr);
(2)  Expansion method with the help of array   arr.slice() arr.concat();
var arr = [1,2,3];
var brr = arr.slice();
var brr = arr.concat();
console.log(arr,brr,arr === brr);

How to determine whether a data is an array

var arr = [2,8,4,6];  // New array() = > object created by constructor = > instantiated object
var obj = {a:1,b:2};  // new Object()

console.log(typeof arr);// 'object'
console.log(typeof obj);// 'object'


instanceof   Determine whether a data is created by a constructor (Incomplete defect)
console.log(arr instanceof Array); // Whether Array is created by the constructor Array (whether it is an instantiated object of Array)
console.log(obj instanceof Object); // Whether obj is created by the constructor Object (whether it is an instantiated Object of Object)

Array.isArray()  Constructor Array Own method   => Pass in a data to determine whether it is an array:true no:false
console.log(Array.isArray(arr));  // true
console.log(Array.isArray(obj));  // false
console.log(Array.isArray(1));    // false
console.log(Array.isArray("100"));// false
console.log(Array.isArray(true)); // false

character string

string number boolean null undefined array object
typeof


 character string     Gets and sets a piece of text

 How strings are created
 1. Literal creation
var str = "hello";  
console.log(str,typeof str);  // "hello"  "string"

 2. Constructor creation
var str = new String("hello");
console.log(str,typeof str); // {"hello"} 'object'
console.log(str+1); 


 var num = 1;
 console.log(num,typeof num);
 var num = new Number(1);
 console.log(num,typeof num,num+1);

 var bool = true;
 console.log(bool,typeof bool);
 var bool = new Boolean(true);
 console.log(bool,typeof bool,bool+true);
 

 Properties of strings
 1.yes length attribute,Table length,Represents the number of characters in a string
 2.Values can be obtained by subscript,However, it cannot be assigned by subscript(Officially decided =>The extension method of the string will not affect the original string,The operation string returns a new string)    Subscript at maximum = length - 1
 3. Can be iterated

Extension method of string

charAt(index) pass in a subscript and return the character corresponding to the subscript. If not found, return ""
var str = "hello world";
var char = str.charAt(6);
console.log(char,str[6]);

var char = str.charAt(100);
console.log(char,str[100]);  // "" 
charCodeAt() passes in a subscript and returns the encoding of the character corresponding to the subscript (ASCII) = > judge the character encoding range
var code = str.charCodeAt(6) // w => 119
var code = str.charCodeAt(4) // o => 111
console.log(code);

code  48-57  =>number
code  65-90  =>Capitalize
code  97-122 =>a lowercase letter
!!! Constructor String method
String.fromCharCode() Constructor String Method of => Transmit one or more character codes => Returns the corresponding character/character string
var char = String.fromCharCode(119);
console.log(char);

var str1 = String.fromCharCode(119,111);
var str1 = String.fromCharCode(72,101,108,108,111);
console.log(str1);
indexOf() returns the position of the first occurrence of a character or a segment of characters in the string. The index does not exist - 1
var str = "good good study , day day up";
var index = str.indexOf("d"); // 3
var index = str.indexOf("day"); // 18
var index = str.indexOf("day123"); // -1
console.log(index);
indexOf(searchChar,startIndex) indexOf() can receive the second parameter as the starting index of the query (0 by default)
var index = str.indexOf("d",4); // 8
var index = str.indexOf("day",19); // 22
console.log(index);
lastIndexOf() returns the position of the last occurrence of a character or a segment of characters in the string. The index does not exist. - 1
Reverse traversal query  length-1 => 0
var str = "good good study , day day up";
var index = str.lastIndexOf("d"); // 22
var index = str.lastIndexOf("d",21); //18
console.log(index);
includes() determines whether a character or a segment of characters exist in the string (ES6)
var str = "good good study , day day up";
console.log(str.includes("d"));
console.log(str.includes("day"));
console.log(str.includes("day123"));
concat() string splicing (splicing multiple character strings to form a new string)
var str1 = "hello";
var str2 = "world";
var str = str1.concat(" ",str2);
var str = str1 + " " + str2;
console.log(str);
String trimming
slice(startIndex,endIndex) string trimming
var str = "good good study , day day up";
var result = str.slice(10,15);  // "study"
var result = str.slice(22,25);     // "day"

slice() Negative values can be accepted  => Length of string + negative
var result = str.slice(-6,-3);     // "day"  -6=>28-6  -3=> 28-3

console.log(result);
substring(startIndex,endIndex) is used in the same way as slice parameter. Negative values cannot be received
 var str = "good good study , day day up";
 var result = str.substring(10,15);  // "study"
 var result = str.substring(22,25);     // "day"
 console.log(result); 
substr(startIndex,length) cuts the string of corresponding length from the position with the subscript startIndex
 var str = "good good study , day day up";
 var result = str.substr(10,5);  // "study"
 var result = str.substr(22,3);     // "day"
 console.log(result); 

innerText and innerHTML

Value and assignment of non form elements

 innerHTML   Gets and sets the html structure(Plain text also gets and sets text)
 innerText   Gets and sets the text structure within the element(If set html The structure will be output as is)

isNaN() passes in a parameter to judge whether it is non numeric. Non numeric returns true and numeric returns false

(it can also be used to judge whether it is a number, and the number returns false)
If the passed in parameter is of type number, judge directly
If the parameter passed in is a data type other than number, it shall be implicitly converted to number before judgment

console.log(isNaN(NaN));
console.log(isNaN(100));
console.log(isNaN("100")); // "100"   => 100 false
console.log(isNaN("")); // ""         => 0   false
console.log(isNaN(true)); // true      => 1   false
console.log(isNaN(null)); // null      => 0   false
console.log(isNaN("100a")); // "100a"  => NaN true
console.log(isNaN(undefined)); // undefined => NaN true

Logical operator extension

If and and or both sides are not Boolean => It is not converted to Boolean value, but follows the rules of short circuit operation(law:As Boolean)

&&  Both true and false are true  =>  Looking for a fake,If you find it, you don't have to look at it
console.log(true&&true);
console.log(true&&false);

console.log(1 && 2);  // 2
console.log(1 && 0);  // 0

console.log(0 && 2);  // 0
console.log(0 && ""); // 0
console.log(1 && 3 && 2); // 2
console.log(1 && null && 2); // null 
The same false is false, and the true is true      => Looking for real ,If you find it, you don't have to look at it
console.log(true||true);
console.log(false||true);

console.log(1 || 2);  //1
console.log(0 || 2);  //2 = > is it used to judge whether there is a value in disguised form?
console.log("" || 2);  //2 = > is it used to judge whether there is a value in disguised form?
console.log(undefined || 2);  //2 = > is it used to judge whether there is a value in disguised form?

Extension method of string

toUpperCase() converts letters to uppercase and returns the converted new string
toLowerCase() converts letters to lowercase and returns the converted new string
 var str = "Hello World";   
 var upStr = str.toUpperCase();
 console.log(upStr);

 var lowStr = str.toLowerCase();
 console.log(lowStr);

 trim()  De duplication of leading and trailing spaces   => Returns a new string
 trimLeft() | trimStart()  De duplication head space   => Returns a new string
 trimRight() | trimEnd()  De duplication head space   => Returns a new string
search match replace split() common usage + use with regular expressions
search() find
Common usage returns the existence of the first occurrence of a character or a segment of characters in a string:Return subscript  (with indexOf())   
var str = "good good study , day day up";
var index = str.search("d");  //3
var index = str.search("day");  // 18
var index = str.search("day123");  // -1
console.log(index);

Use with regular expressions   => Returns the position of the first occurrence of a character or a segment of characters that meet the rule in a string 
var str = "good good study , Day123 dAy up";
var reg = /day/; //  Case insensitive - 1
var reg = /day/i; // Ignore case d|a|a y|y day day day day day day day day
var reg = /day/ig; // G global match (match all in the whole string without g, and only one is matched by default), but the G modifier of the search method has no effect

var index = str.search(reg)
console.log(index);*/
Match
Common usage will match the content(A string or a segment of string)Return in array  (Only one is matched by default)  existence:The returned array does not exist:null
var str = "good good study , day day up";
var arr = str.match("day"); // ["day",index:18]
var arr = str.match("Day");
console.log(arr); 

 Use with regular expressions   => Put a string or a segment of string that meets the rule into the array(By default, only one fit modifier is matched g You can match the entire string)
 var str = "good good study , Day dAy up";
 var reg = /day/;   // day
 var reg = /day/i;  // Ignore case d|a|a y|y = > day day day day day day day day
 var reg = /day/ig;  // Ignore global case matching
 var arr = str.match(reg);
 console.log(arr);
replace(oldStr,newStr)
 Common usage replaces a character or a segment of a string with another string (Replace the original string with a new string)  =>New string  (Only one is matched by default)

var str = "good good study , day day up";
var newStr = str.replace("day","money");
 console.log(newStr);

 Use with regular expressions => Replace one or a segment of characters that match the rule with another string (By default, only one fit modifier is replaced g You can replace the entire string)

 var str = "good good study , Day dAy up";

 var reg = /day/;   // day
 var reg = /day/i;   // ignore case
 var reg = /day/ig;   // ignore case
 var newStr = str.replace(reg,"money")
 console.log(newStr);


 Remove all spaces
var str = "    good good study ,    Day dAy up     ";
var reg = / /g;  
var newStr = str.replace(reg,"");
console.log(newStr); 
split()
Common usage splits a string into arrays with specific characters
var str = "a-b-c-d";
var list = str.split("-");
var list = str.split("");  // Split each character
console.log(list);

Use with regular expressions => Splits a string into an array with one or more characters that match the rules
var str = "a-b-c-d";

var reg = /-/g; //Use - split
var list = str.split(reg);  // Split each character
console.log(list);
join()
 var list = ["a","b","c","d"];
 var str = list.join("-");
 console.log(str);  // "a-b-c-d"

regular expression

Regular expression
It is a matching pattern of strings (which can be used to verify string matching in forms) = > in short, it is to match strings with established rules

 user name
 Upper and lower case letters by numbers _ $ form , 6-12 position,And cannot start with a number    /^[a-zA-Z_][0-9a-zA-Z_]{5,11}$/ig

 password
 Upper and lower case letters by numbers _ Composition 6-12 position 

 mailbox
 *********@qq.com

 Composition of regular expressions 
 (1)  rule    /day/
 (2)  Modifier    i(ignore case ignore case)  g(Global matching global)

 Creation of regular expressions
 
 1. Literal creation shortcut(Cannot splice variables)
 var a = 100;
 var reg = /day/ig; 
 console.log(reg);

 2. Constructor creation    (You can splice variables)
 var a = 100;
 var reg = new RegExp("d"+a+"y","ig");
 console.log(reg);

 3. Combined usage  (Constructor RegExp You can also receive a regular expression)
 var reg = new RegExp(/day/ig);
 console.log(reg);

Date object

Date object = > you can get and set the time

 How to create a date object?  
 Constructor creation   (obtain|set up)

 (1) Get current time  => China standard time(GMT(UTC) + 0800)
 GMT(UTC)   World time(Greenwich) => Date The object records 00 from January 1, 1970:00:00 Milliseconds since start   
var date = new Date();
 console.log(date);

 (2) Set a time  
 a. Receive a time formatted string(Time format "2021/10/11 12:12:12")
var date = new Date("2021-11-11 12:12:12");
 console.log(date);

 b. Multi parameter transmission(Specify year, day, hour, minute and second respectively)  =>
 be careful: Month parameter: 0-11  => Month parameters = Expected month - 1
var date = new Date(2021,10,11,12,12,12);
 console.log(date);

 c. Can receive a millisecond (There is only one parameter and is number type) 
var date = new Date(0);
var date = new Date(1000000000000);  // > 1970
var date = new Date(-1000000000000); // < 1970
 console.log(date);

 d. new Date()Can receive a date object  => You can get a new date with the same time as the original date (There are methods that affect the original date in the extension methods of date objects => Copy first in order not to affect)
var date = new Date("2021-11-11 12:12:12");
var date1 = new Date(date); // date -> ms -> new Date(ms)
console.log(date);
console.log(date1);

Character statistics

1.  Known string"aabccd"The following functions are realized by programming.
 
(1) String de duplication  "abcd"
var str = "aabccd";
var uniStr = "";
for (var char of str) {
    if (uniStr.indexOf(char) == -1) {
        uniStr += char;
        // uniStr = uniStr.concat(char);
    }
}
console.log(uniStr); // "abcd"

(2) Count the number of occurrences of each character, and the result is displayed   a2b1c2d1     Character statistics(Total number of occurrences per character)
var countStr = "";
for(var i=0;i<uniStr.length;i++){ // "ABCD" = > each
    var uniChar = uniStr.charAt(i); //"a"
    var count = 0;
    for(var j = 0; j < str.length; j++){
        var item = str.charAt(j);
        if(uniChar == item){
            count++;
        }
    }
    countStr += uniChar+count;
} 
console.log(countStr); 
var countStr = "";
for(var i=0;i<uniStr.length;i++){ // "ABCD" = > each
    var uniChar = uniStr.charAt(i); //"a"
    var reg = new RegExp(uniChar,"g"); //   /a/g
    var list = str.match(reg);
    console.log(reg,list);
    countStr += uniChar+list.length;
} 
console.log(countStr);
var arr = [ "a" ,"a", "b" ,"c" ,"c" ,"d"];
var str = "aabccd";
var obj = {};
for (var char of str) { // "aabccd"  => "a" "a" "b" "c" "c" "d"
    if (obj[char]) { // Take each character as the key name of the object (the key name is unique)
        obj[char]++;  //  obj[char] = obj[char] + 1
    } else {
        obj[char] = 1;
    }
}
console.log(obj);
var countStr = "";
for(var key in obj){
    console.log(key,obj[key]);
    countStr += key + obj[key];
}
console.log(countStr);

(3)(Original string: aaaabbbbbbbccdaaaaa;After compression: a4b7c2d1a5)  Compression statistics (Number of repetitions of adjacent characters)

var str = "aaaabbbbbbbccdaaaaa";
var count = 0;
var countStr = "";
for(var i = 0; i < str.length;i++){
    if(str.charAt(i) == str.charAt(i+1)){
        count++;
    }else{
        count++;
        countStr += str.charAt(i) + count;
        count = 0;  //Reset to 0 for next recount
    }
}
console.log(countStr);

timer

var timer = setInterval(function(){},1000)//Set the timer and trigger the function every 1000 milliseconds
clearInterval(timer)//Clear specified timer

Set timer

Pass a function as an argument into another function,Executed on behalf of another function  =>  Callback function
 Can be understood as => Specify the contents to be implemented in advance(Put in function)  

setInterval(callbackFn,interval,arg1,arg2...argN);   Specify an action every specific time(function)
callbackFn  Pass in a function to specify the content to be executed at each interval  (The content to be executed is specified in advance => function(Named function anonymous function => Pass the function as an argument))
interval    Interval time(The unit is milliseconds)
arg1,arg2...argN  As callbackFn Actual parameters passed in

Return value number => The number of the timer

be careful: The timer needs to wait for the corresponding interval from start to execution

If callbackFn Receive parameters required:
(1)  You can receive a string in the form of a function call  => This string can be used internally as a timer JS Syntax parsing 
var timer = setInterval( 'countDown("2021-11-11 00:00:00")' ,1000);

(2) Change to nested calls to functions   => Anonymous functions are executed at regular intervals => call countDown
var timer = setInterval( function(){
countDown("2021-11-11 00:00:00");
} ,1000);

(3) If callbackFn Parameters that need to be received can be passed in from the third parameter in turn
var timer = setInterval( countDown ,1000,"2021-11-11 00:00:00");

It is required to print 111 on the console at regular intervals

setInterval("console.log('hahaahhahahh')",1000)

setInterval(function(){
    console.log(11111);
},1000)

setInterval(console.log,1000,1111,2222,3333);

Template string

ES6 Template strings can be represented by interpolation statements ${} => Splicing variables and executing simple expressions

Extension method of date object_ obtain

var date = new Date();  //Date object
console.log(date);

Get the day, day, day, week, hour, minute, second, millisecond
var year = date.getFullYear();
console.log(year);

Get month  => month(0-11)
be careful:If you want to show the effect, the actual month = Gets the month of the month + 1
var month = date.getMonth();
console.log(month);
console.log("Actual month:",month+1);

get date 
var day = date.getDate();
console.log(day);

Get week  => week(0-6   0:Sunday)
var week = date.getDay();
console.log(week);

var hour = date.getHours();
console.log(hour);

var minute = date.getMinutes();
console.log(minute);

var second = date.getSeconds();
console.log(second);

var millisecond = date.getMilliseconds();
console.log(millisecond);

Gets the total number of milliseconds corresponding to the current date
var ms = date.getTime();
console.log(ms);

console.log("--------------------UTC--------------------------------");
var year = date.getUTCFullYear();
console.log(year);

Get month  => month(0-11)
be careful:If you want to show the effect, the actual month = Gets the month of the month + 1
var month = date.getUTCMonth();
console.log(month);
console.log("Actual month:",month+1);

get date 
var day = date.getUTCDate();
console.log(day);

Get week  => week(0-6   0:Sunday)
var week = date.getUTCDay();
console.log(week);

var hour = date.getUTCHours();
console.log(hour);

var minute = date.getUTCMinutes();
console.log(minute);

var second = date.getUTCSeconds();
console.log(second);

var millisecond = date.getUTCMilliseconds();
console.log(millisecond);

Extension method of date object_ set up

Set the year, month, day, hour, minute, second, millisecond of the date object 
Return value: The number of milliseconds corresponding to the set time
 Affect original date object : influence

!!!!!!!!!! 
Note that the setting of month, day, hour, minute, second and millisecond exceeds the maximum threshold => Carry one bit less than the minimum critical value => Excuse me 


Set Year 
var result = date.setFullYear(2500);
console.log(result);
console.log(date);


Set month parameter range(0-11)
var result = date.setMonth(0);    //  2021-1-12
var result = date.setMonth(-1);    //  2021-(-1)-12  => 2020-12-12
var result = date.setMonth(12);    //  2021-(13)-12  => 2022-1-12
console.log(result);
console.log(date);

Set date    
The 0th day of this month is the last day of last month
 The 0th day of next month is the last day of this month

var result = date.setDate(1); // 2021-10-1
var result = date.setDate(0);   // 2021-10-0 => 2021-9-30
var result = date.setDate(32)   // 2021-10-32 => 2021-11-1
console.log(result);
console.log(date);

date.setHours(12);
date.setMinutes(21);
date.setSeconds(12);
date.setMilliseconds(123);

console.log(date);   

Sets the number of milliseconds corresponding to the date
date.setTime(0);
console.log(date);

Date formatting_ encapsulation

2021-09-04 21:49:00
2021-09-04 21:49
2021-09-04
21:49:00

2021/09/04 21:49:00
2021/09/04 21:49
2021/09/04

Encapsulates a function that formats and outputs time => Specify time format when exporting?
pattern The formal parameter is used to receive the time format
date    Optional filling(Get current time by default, You can also pass in a string in event format,Date object,Msec )
function dateFormat(pattern,date){
    var pattern = "YY-MM-DD hh:mm:ss";
    Judge whether there is a parameter
    if(date){ // Parameter = > get a new time according to the passed in
        date = new Date(date);
    }else{ //No = > get the current time by default
        date = new Date();
    }

    var year = date.getFullYear();
    var month = date.getMonth()+1;
    var day = date.getDate();

    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();
    
    Chain operation essence replace() Method returns:The replaced new string can still be called replace method
   return pattern.replace("YY",year).replace("MM",beauty(month)).replace("DD",beauty(day)).replace("hh",beauty(hour)).replace("mm",beauty(minute)).replace("ss",beauty(second));
}

function beauty(num) {
    return num < 10 ? "0" + num : num;
}


console.log(dateFormat("YY-MM-DD hh:mm:ss"));
console.log(dateFormat("YY-MM-DD hh:mm"));
console.log(dateFormat("YY-MM-DD"));
console.log(dateFormat("hh:mm:ss"));
console.log(dateFormat("YY/MM/DD hh:mm:ss"));

console.log(dateFormat("YY/MM/DD hh:mm:ss","2021-12-31"));
console.log(dateFormat("YY/MM/DD hh:mm:ss",1000000000000));

Encapsulates a function that formats and outputs time => Specify time format when exporting?
    pattern The formal parameter is used to receive the time format
    function dateFormat(){
    var pattern = "YY-MM-DD hh:mm:ss";
    var date = new Date();

    var year = date.getFullYear();
    var month = date.getMonth()+1;
    var day = date.getDate();

    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();

    pattern = pattern.replace("YY",year);  // The replaced new string is assigned to the original variable
    pattern = pattern.replace("MM",month);
    pattern = pattern.replace("DD",day);
    pattern = pattern.replace("hh",hour);
    pattern = pattern.replace("mm",minute);
    pattern = pattern.replace("ss",second);
    console.log(pattern);
    
    //The replace() method of chain operation returns a new string after replacement, which can still call the replace method
    pattern = pattern.replace("YY",year).replace("MM",month).replace("DD",day).replace("hh",hour).replace("mm",minute).replace("ss",second);
    console.log(pattern);
 }

Setting the date does not affect how to the original date object

var date = new Date();
console.log(date);

Set the year, month, day, hour, minute, second, millisecond of the date object 
Return value: The number of milliseconds corresponding to the set time
 Affect original date object : influence
 Get a new date object with the same time as the original date object
var date1 = new Date(date); // Date = > Ms = > New Date object
var result = date1.setFullYear(2500);
console.log(result);
console.log(date1);
console.log(date);

Delay device

The timer executes specific content at regular intervals (Always execute as long as you don't clear)

The delayer delays the execution of specific content for a period of time (Execute only once)

Set delay
setTimeout(callbackFn,delay,arg1,arg2...argN)
callbackFn   Pass in a function that specifies what to execute after waiting a specific time  (The content to be executed is specified in advance => function(Named function anonymous function => Pass the function as an argument))
delay        delay time (Company:millisecond)
arg1...argN  If callbackFn If the parameter needs to be received, it will be transmitted back from the third parameter

Return value: Number of delay device

Clear delay 
clearTimeout(Number of delay device)     It is generally used to clear the delayer and change the timer

DOM beginner

JS form 
 ECMAScript  =>ES5 (ES6)
 BOM(Browser Object Model)   Browser object model => The interface and method for operating the browser are provided
 DOM(Document Object Model)   Document object model =>  Provides interfaces and methods for operating documents

 window => document => html => body => ...  


 HTML DOM It is about how to get, modify, add or delete HTML Element, i.e. operation HTML Element of
 In short  HTML Addition, deletion, modification and query of elements


 be careful:  About documents document
 whole html The page loads into the browser and becomes part of the document
 All elements in the page can be accessed through the document (Dynamically access and update the content, structure, and style of documents)
console.log(document);


 JS New node concept
 according to W3C of HTML DOM Standards, HTML Everything in the document is a node:
 The entire document is a document node        => document
 each HTML An element is an element node      => h1-h6 p div ul li span 
 HTML The text within the element is a text node    => text 
 each HTML Attributes are attribute nodes      => class="" id="" title=""
 Annotations are annotation nodes               => 

 The essence of nodes => object

 Hierarchical relationship(Nodes in the node tree have hierarchical relationships with each other.)
 Parent node 
 Child node
 Sibling node

 Root node(html)   The root node has no parent node

Method to get element node

 Method to get element node
 (Get all the elements of the page through the document)
 document.getElementById();          In document,adopt id Get element name=>Element not found:null
 document.getElementsByClassName()   In document,adopt class Get element name=>Collection not found:[]
 document.getElementsByTagName();    In document,Get element by tag name=>Collection not found:[]
 document.getElementsByName()        In document,adopt name Property get element get=>Collection not found:[]  (Generally used for form elements)

Method to get element node_ Restrict parent element

Can I get the corresponding child element through the parent element  (Limit query scope)
Child elements can be obtained from parent elements  =>There are limitations (Can only be obtained through the parent element getElementsByClassName getElementsByTagName)

Method of element node

Method of element node  => Operation attribute node(Property addition, deletion, modification and query)

Attribute node (Write in the label and separate the label name with a space)  => Element dependent nodes
 Operate attribute nodes through methods related to element nodes

Element.getAttribute(key)      Get the attribute value corresponding to the attribute name
Element.setAttribute(key,val)  Set the attribute value corresponding to the attribute name  (If not, add and modify)
Element.removeAttribute(key)   Delete attribute corresponding to attribute name

var one = document.getElementsByClassName("one")[0]; // Node essence = > object
console.log(one);
obtain
var _class  = one.getAttribute("class");
console.log(_class);

var id = one.getAttribute("id");
console.log(id);

var title = one.getAttribute("title");
console.log(title);
Settings (modify)
one.setAttribute("class","first");
one.setAttribute("id","demo");
one.setAttribute("title","Hello");
console.log(one);
delete
one.removeAttribute("class");
one.removeAttribute("id");
one.removeAttribute("title");
console.log(one);
Add (add without setting = > Modify with setting)
one.setAttribute("class","first");
one.setAttribute("id","demo");
one.setAttribute("title","Hello");

be careful H5 start,Allow users to customize attributes(Specify the attribute name and attribute value yourself)

(1) with data-Attribute name
(2) Define yourself at will  asd  abc
one.setAttribute("asd","asd");
one.setAttribute("data-index","0");

var asd = one.getAttribute("asd");
var index = one.getAttribute("data-index");
console.log(asd);
console.log(index);

one.removeAttribute("asd");
one.removeAttribute("data-index");

console.log(one);
document.getElementsByClassName() gets the node list of the same class attribute. IE8 and below do not support encapsulating a method. Find the element with the specified class name from all elements of the page and put it in the array = > return
function myGetElementsByClassName(className){
    var className = "list";  //class name to find

    var list = document.getElementsByTagName("*");  //Get all elements in the page
    console.log(list);

    var arr = [];
    for(var i=0;i<list.length;i++){
        var ele = list[i];
        console.log(ele);
        var _class = ele.getAttribute("class");
        console.log(_class);
        if(_class){  // Value = > contains class name
            var classList = _class.split(" "); 
            console.log(classList);
            if(indexOf(classList,className)!=-1){
                arr.push(ele);
            }
        }
    }
    return arr;
}


function includes(list,char){
    var flag = false;
    for(var i = 0; i < list.length; i++){
        var item = list[i];
        if(item === char){
            flag = true;
            break;
        }
    }
    console.log(flag);
    return flag;
}

Returns the first occurrence of an element in an array:Return subscript does not exist:-1
function indexOf(list,char){  
    var index = -1;
    for(var i = 0; i < list.length; i++){
        var item = list[i];
        if(item === char){
            index = i;
            break;
        }
    }
    console.log(index);
    return index;
}

Tags: Javascript node.js html5

Posted on Fri, 15 Oct 2021 01:48:48 -0400 by Stevis2002