current position:Home>The foundation of JavaScript

The foundation of JavaScript

2022-04-29 08:08:53Chen Chen is trying

JavaScript Basics

JavaScript brief introduction

A complete JavaScript The implementation should consist of the following three parts :

  • ECMAScript standard
  • DOM Document object model
  • BOM Browser object model

JS It's also an object-oriented language

JS Where to write

  1. Can be Js Write the code into the specified attribute of the tag . It is not recommended to use

    <button onclick="alert('hello');"> I'm the button </button>  
    <a href="javascript:alert('aaa');"> Hyperlinks </a>  
    
  2. Can be written to script In the label

    <script type="text/javascript"> // To write js Code   </script>  
    
  3. You can write code to external js In file , And then through script The tag introduces it to

    script Once the tag is used to import external files , You can't write code , Even if the browser is written, it will ignore , If necessary, you can create a new script Tags are used to write internal code

    <script type="text/javascript" src=" File path "></script>  
    

Output statement

/* This statement will pop up a warning box in the browser window  */
alert(" What to output ");  
/* The content will be written to body In the label , And show... On the page  */
document.write(" What to output ");   
/* This content will be written to the console of the developer tool */
console.log(" What to output ");    

Basic grammar

js Function declarations don't need ; A semicolon , But the assignment statement needs to add ; A semicolon

function functionName(arg0,arg1,arg2){
      
// Function declaration  
}  
var functionName=function(arg0,arg1,arg2){
      
// Function expression  
};( Pay attention to the semicolon )  

notes :

  • Single-line comments

    // The comment  
    
  • Multiline comment

    /*  The comment  */  
    

JS Case sensitive

JS Each statement in the is marked with a semicolon (;) ending . If you don't write a semicolon , The browser will automatically add , But it will consume some system resources , And sometimes , The browser will add the wrong semicolon , So in development, the semicolon must be written

JS Multiple spaces and line breaks are automatically ignored in , So we can format the code .

Literals and variables

Literal

Literal values are actually fixed values , such as :1 2 3 4 true false null NaN “hello”

The literal amount cannot be changed .

Because the literal quantity is not very convenient to use , So in JS Literal values are rarely used directly in

Variable

Variable can be used to store literal amount , And can save any literal amount

In development , Literal values are usually used through variables , Instead of using literal , Moreover, the literal quantity can also be described by variables

Declare variables : Use var Keyword to declare a variable

var a;  

Assign values to variables :

a = 1; 

Declaration and assignment are performed at the same time :

var a = 456;   

identifier

stay JS All the contents that can be named independently in , Can be considered as an identifier .

such as : Variable name 、 Function name 、 Property name

When naming an identifier, you should follow the specification of the identifier :

  1. Identifiers can contain letters 、 Numbers 、_、$
  2. Identifier cannot begin with a number
  3. Identifier cannot be JS Keywords and reserved words in
  4. The identifier generally adopts hump naming method :xxxYyyZzz

data type

Six data types

JS There are six types of data in 5 Basic data types +object( Reference data type )

  • String character string
  • Number The number
  • Boolean Boolean value
  • Null Null value
  • Undefined Undefined
  • Object object

The basic data types are 5 individual

1.String character string

JS Strings in need to be enclosed in quotation marks . Double or single quotation marks are OK , But don't mix it up . Use... In a string \ As escape character

\' ==> '
\" ==> "
\n  ==>  Line break 
\t  ==>  tabs 
\\  ==> \

2.Number The number

JS All integers in are Number type , Including integers and floating-point numbers

typeof Operator can check the data type of a variable

grammar :typeof Variable

Use typeof Operator checking string , Returns the "string"

Use typeof Check one Number Type of data , Returns the "number"( Include NaN and Infinity)

Use typeof When checking a Boolean value , Returns the "boolean"

Use typeof Check one Null The value of type "object"

Use typeof Check one Undefined Value of type , Returns the "undefined"

The value of maximum energy :Number.MAX_VALUE=1.7976931348623157e+308

Greater than 0 The minimum value of :Number.MIN_VALUE=5e-324

stay JS The operation of integer in can guarantee the accuracy , If you use JS Do floating point operations , It's possible to get an imprecise result .

Special numbers : Can assign to variable

  • Infinity It's just infinite a = Infinity , Capable of assignment
  • -Infinity Negative infinity
  • NaN Illegal number (Not A Number)

The representation of other base numbers :

  • 0b Start with binary , But not all browsers support
  • 0 Start with octal
  • 0x The beginning is hexadecimal
// image "070" This string , Some browsers will look like 8 Hexadecimal parsing , Some will take 10 Hexadecimal parsing 
a = "070";
console.log(a);
// resolvent : stay parseInt() Pass a second parameter in , To specify the base of the number 
a = parseInt(a,10);
console.log(a);

3.Boolean Boolean value

Boolean values are mainly used for logical judgment , There are only two Boolean values

true The truth of logic

false The falsehood of logic

4.Null Null value

Null values are specifically used to represent empty objects ,Null There is only one value of type null. Use typeof Check one Null The value of type "object"

var a = null;
console.log(typeof a);
// Output :"object"

5.Undefined Undefined

If you declare a variable but do not assign a value to it , At this point, the value of the variable is undefined

There is only one value for this type undefined

Use typeof Check one Undefined Value of type , Returns the "undefined"

Reference data type

Object object

Type conversion

Type conversion mainly refers to the conversion of other data types , Convert to String、Number or Boolean

Convert to String

Mode one ( Cast ):

Call the... Of the converted data toString() Method , This method does not affect the original variable , It will return the result of the transformation .

Example :

var a = 123;
a = a.toString();

Be careful : This method does not apply to null and undefined

Because there are no methods in these two types of data , So call toString() When an error

Mode two ( Cast ):

call String() function , The transformed data is passed to the function as parameters

Example :

var a = 123;  
a = String(a);  

principle : about Number Boolean String Will call them toString() Method to convert it to a string . about null value , Convert directly to a string "null". about undefined Convert directly to a string "undefined"

Mode three ( Implicit type conversion ):

For any data type +" "

Example :

var a = true;  
a = a + ""; 

principle : and String() The function is the same

Convert to Number

Mode one ( Cast ):

call Number() function

Example :

var s = "123";  
s = Number(s); 

The conversion situation :

  • character string --> Numbers
    1. If it's a string of pure numbers , Then it is directly converted to the corresponding number
    2. If there is non numeric content in the string , Convert to NaN
    3. If it's an empty string or a pure space string , Convert to 0
  • Boolean value --> Numbers
    • true Convert to 1
    • false Convert to 0
  • Null value --> Numbers
    • null Convert to 0
  • Undefined --> Numbers
    • undefined Convert to NaN

Mode two ( Cast ):

This method is specifically used to deal with strings :

  • parseInt() Convert a string to an integer . Take out the valid integer content in a string , And then convert to Number

    var a = "123.456px";  
    a = parseInt(a); //123 
    
  • parseFloat() Convert a string to a floating point number . It can get valid decimals .

    var a = "123.456px";  
    a = parseFloat(a); //123.456 
    

If right or wrong String Use parseInt() or parseFloat(), It will Convert it to String And then operate .

Mode three ( Implicit type conversion ):

Use one dollar + For implicit type conversion

Example :

var a = "123";  
a = +a;  

principle : and Number() The function is the same

Convert to Boolean

Mode one ( Cast ):

Use Boolean() function

Example :

var s = "false";  
s = Boolean(s); //true 

The conversion situation :

  • character string --> Boolean : Except for empty strings, the rest are true
  • The number --> Boolean : except 0 and NaN The rest are all true
  • null、undefined --> Boolean : All are false
  • object --> Boolean : All are true

Mode two ( Implicit type conversion ):

Do two non operations for any data type , You can convert it to a Boolean value . The following example :

var a = "hello";  
a = !!a; //true 

Basic grammar

Operator

Operators are also called operators , Operators allow you to operate on one or more values , And obtain the operation result

typeof Operator

The data type used to check a variable

grammar :typeof Variable

It returns a string describing the type as the result

Arithmetic operator

  • +  Add two values and return the result

  • -  Subtract two values and return the result

  • *  Multiply two values and return the result

  • /  Divide two values and return the result

  • %  Carry out the remainder operation on two values and return the result

** Besides addition , Right Number When the value of type is evaluated , Will be converted to Number And then do the operation .** This feature can be used for implicit type conversion .

And in addition , If you add two strings , Will do string operation , Concatenate two characters into a string .

Add any value and string , Will be converted to a string first , And then put it together . You can take advantage of this , Convert any data type to String type , It belongs to implicit conversion .

Unary operator

Unary operators only need one operand

One dollar +

It's a plus sign , There is no effect on the value , But you can convert a non number to a number
Example :

var a = true;  
a = +a;  

One dollar -

It's a minus sign , You can reverse the sign bit of a number
Example :

var a = 10;  
a = -a;  

Self increasing ++

Self increment can make the variable increase on the basis of the original value 1

Self increasing can be divided into front ++(++a) And after ++(a++)

Whether it's ++a still a++ Will immediately increase the original variable 1

The difference is ++a and a++ The values are different :

  • ++a The value of is equal to the new value of the variable ( The value after self increase ) First operation and then self increment
  • a++ The value of is equal to the original value of the variable ( Value before autoincrement ) First increment and then operation

Self reduction –

Self subtraction can reduce the variable based on the original value 1

Self subtraction can be used front –(--a) And after –(a–)

Whether it's ++a still a++ Will immediately reduce the original variable 1

The difference is a and a The values are different :

  • a The value of is the new value of the variable ( The value after subtraction )
  • a The value of is the original value of the variable ( The value before subtraction )

Logical operators

  • ! Not

    1. A non operation can negate a Boolean value ,true change false false change true
    2. When using... For non Boolean values ! when , It will be converted to a Boolean and then negated
    3. We can use ! To convert other data types to Boolean values :!!10【 You need to do two non operations 】
  • && And

    1. && The values on both sides of the symbol can be calculated
    2. Only the values at both ends are zero true when , Will return true. As long as there is one false It will return false
    3. JS The and in is a short-circuit and , If the first value is false, The second value is no longer checked
    4. For non Boolean values , It's going to convert it to a Boolean and do the operation , And return the original value rule :
      • If the first value is false, Returns the first value
      • If the first value is true, Then return the second value
  • || or

    1. || You can do or operate on the values on both sides of the symbol
    2. Only at both ends false when , Will return false. As long as there is one true, It will return true.
    3. JS Or a short circuit or , If the first value is true, The second value is no longer checked
    4. For non Boolean values , It's going to convert it to a Boolean and do the operation , And return the original value . The rules :
      • If the first value is true, Returns the first value
      • If the first value is false, Then return the second value

Assignment operator

=: You can assign the value on the right side of the symbol to the variable on the left

+=

a += 5  amount to  a = a+5    
var str = "hello";  str += "world";  

-=

a -= 5   amount to  a = a-5  

*=

a *= 5  amount to  a = a*5  

/=

a /= 5  amount to  a = a/5	  

%=

a %= 5  amount to  a = a%5 

Relational operator

The relational operator is used to compare the size relationship between two values :>>=<<=

The rules of relational operators are the same as in mathematics , Used to compare the relationship between two values , If the relationship holds, return true, If the relationship is not established, return false.

If the two values being compared are non numeric , It will be converted to Number Then compare .

If the two values being compared are strings , The string will be compared Unicode code , It doesn't translate into Number. When comparing character codes, they are compared bit by bit .

If you compare two string arrays , You may get unexpected results . We need to transform first .

Equality operator

equal , Judge whether the left and right values are equal , If equal returns true, If you don't wait to return false

==

equal , The two values are automatically type converted , If Compare different types , It will be converted to the same type and then compared , After conversion, it also returns true.

!=

Unequal , Judge whether the left and right values are not equal , If not, return to true, If equal, return false

You can also do automatic type conversion .

===

Congruence **, Judge whether the left and right values are congruent , It's similar to equality , It's just that it doesn't do automatic type conversion , If the two values are of different types , Then return directly false**

!==

Incongruence **, It's similar to inequality , But it doesn't do automatic type conversion , If the two values are of different types , It will go straight back to true**

Special value :

  • null and undefined. because undefined Derived from null, therefore null == undefined Returns the true. however null === undefined Returns the false.

  • NaN.NaN Not equal to any value , The report includes itself NaN == NaN【false】 Judge whether a value is NaN, Use isNaN() function .

Ternary operator

grammar : Conditional expression ? sentence 1: sentence 2;

Execute the process : First, evaluate and judge the conditional expression . If the result is true, Then execute the statement 1, And return the execution result ; If the result is false, Then execute the statement 2, And return the execution result .

priority : As in Mathematics ,JS Operators in are also prioritized , such as : Multiply and divide first and then add and subtract first and then. For specific priority, please refer to the table of priority , The higher the priority is in the table , The higher the priority, the higher the priority , Same priority , Count from left to right .

Priorities don't need to be remembered , If you encounter uncertainty , Use () To change priorities .

Flow control statement

Programs are executed from top to bottom , The order of program execution can be changed by flow control statement , Or repeatedly execute a certain program .

Code block : stay JS Can be used in {} To group statements , The same {} The statements in are a set of statements , One {} The statement in is called a code block .JS The code blocks in are only used for grouping , There's no other use .

{
    
	alert("hello");
	console.log(" Hello ");
	document.write(" sentence ");
}

Conditional statements

Conditional statements are also called if sentence , He can judge before executing a statement , The statement will not be executed until the condition is established .

Grammar 1 :

if( Conditional expression ){
      
    sentence ...  
}  
  Execute the process :  
 if Statement execution time , Will evaluate the conditional expression first 
  If the value is true, execute if The following sentence 
  If the value is false, Do not perform  

Grammar II :

if( Conditional expression ){
      
	 sentence ...  
}else{
      
	 sentence ...  
} 
  Execute the process :  
	if...else Statement execution time , Will evaluate the conditional expression ,  
		 If the value is true, execute if The following sentence   
		 If the value is false, execute else The following sentence   

Grammar 3 :

if( Conditional expression ){
      
	 sentence ...  
}else if( Conditional expression ){
      
	 sentence ...  
}else if( Conditional expression ){
      
	 sentence ...  
}else if( Conditional expression ){
      
	 sentence ...  
}else{
      
	 sentence ...  
}	  
  Execute the process   
	 if...else if...else Statement execution time , Will evaluate the conditional expression from top to bottom ,  
		 If the result is true, Then execute the current if The following sentence , After execution, the statement ends .  
		 If the result is false, Then continue to judge down , Until it's found for true Until .  
		 If all the conditional expressions are false, execute else The following sentence   

Conditional branch statement

switch Sentence syntax :

switch( Conditional expression ){
      
	case  expression :  
		 sentence ...  
		break;  
	case  expression :  
		 sentence ...  
		break;  
	case  expression :  
		 sentence ...  
		break;  
	default:  
		 sentence ...  
		break;  
}  
 Execute the process :
switch...case... Statement at execution time , Will in turn case The value of the following expression and switch After the expression of the value of congruent comparison 
 If the comparison is false, Then continue to compare down ;
 If the comparison is true, From the present case Start executing code down at ;
 If all case The judgment is that false, From default Start executing code at .

Loop statement

Some statements can be executed many times through loop statements

while loop :

while( Conditional expression ){
      
     sentence ...  
}  
 Execute the process :
while Statement at execution time , Will evaluate the conditional expression first 
 If the result is false, Then stop the cycle ;
 If the result is true, Then execute the loop body ;
 Loop body execution completed , Continue to evaluate the conditional expression ;
 And so on 

do…while loop :

do{
      
 sentence ...  
}while( Conditional expression )  
 Execute the process :do...while When executed , Will execute first do After the cycle body , And then judge the conditional expression , If the result is false, Then stop the cycle . If the result is true, Then continue to execute the loop body , And so on 

do while and while The difference between :

while: Judge before you execute

do…while: Execute before judge

do…while You can make sure that the loop body is executed at least once .

for loop

for(① Initialization expression  ; ② Conditional expression  ; ④ Update expression ){
      
    ③ sentence ...  
}  
 Execute the process :
①  Initialization expression , Initialize a variable ;【 It's only going to be executed once 】
②  Conditional expressions are evaluated ,
 	 If false Then stop the cycle ,
 	 If the result is true, execute ③ The loop body ;
④  Loop body execution completed , Execute update expression , Update variables ;
 After the update expression is executed, repeat ②

You can create a... For a loop statement label To identify the current loop . grammar :label Loop statement

Use break When the sentence is , Can be in break Followed by a label, such break Will end the specified cycle , Not the latest .

outer:
for(var i=0 ; i<5 ; i++){
    
	console.log("@ The outer loop "+i)
	for(var j=0 ; j<5; j++){
    
		break outer;
		console.log(" Inner circulation :"+j);
    }
}

Dead cycle :

while(true){
      

}  

for(;;){
      

}
// Turn on the timer .test For the name of the counter , Used as an identifier for a timer .
console.time("test");
// Stop timers 
console.timeEnd("test");

object (Object)

The object is JS Reference data types in

Object is a composite data type , Multiple attributes of different data types can be saved in the object

Use typeof When checking an object , Returns the object

Classification of objects :

  1. Built in objects

    • from ES Objects defined in the standard , In any ES Can be used in the implementation of
    • such as :Math String Number Boolean Function Object…
  2. Host object

    • from JS Object provided by the running environment of , At present, it mainly refers to the objects provided by the browser
    • such as BOM DOM
  3. Custom object

    • Objects created by developers themselves

Create objects

  1. Mode one

    /* Use new When calling a function with keyword, the constructor 【controller】, Constructor is a function specifically used to create objects .*/
    var obj = new Object();  
    
  2. Mode two

    var obj = {
          }; 
    

Add properties to the object

 object . Property name  =  Property value ;
/* Special attribute names can be used in this way .  When I pick it up : object [" Property name "].  This way is more flexible , stay [] You can pass a variable directly in , In this way, the value of the variable will read which attribute */
 object [" Property name "] =  Property value ;
obj.name=" The Monkey King ";
obj["123"]=789;
var n = 123;
console.log(obj["123"]);
console.log(obj[n]);

There is no requirement for the property name of the object , There is no need to follow the specification of identifiers , But in development , Try to write according to the identifier .

Property values can also be of any data type .

Read the properties in the object

 object . Property name 
 object [" Property name "] //" Property name " You can make string constants , It can also be a string variable 

If you read a property that is not in an object , It doesn't report errors , It's back to a undefined

Modify the property value of an object

 object . Property name = The new value 
obj.name="tom";

Delete attributes from objects

delete  object . Property name 
delete  object [" Property name "]

Traverse

Use in Check whether the object contains the specified property . If the attribute is included in the object , Then return to true; If not, return false.

grammar :“ Property name ” in object

   Loop through the object's own and inherited enumerable properties ( Not included Symbol attribute ).
var obj = {
    '0':'a','1':'b','2':'c'};
  
for(var i in obj) {
      
     console.log(i,":",obj[i]);  
}  

Use object literal , Add properties directly to the object when you create it . grammar :

var obj = {
      
     Property name : Property value ,  
     Property name : Property value ,  
     Property name : Property value ,  
     Property name : Property value   
} 

The literal property name of an object can be quoted or not , It is not recommended to add . If you want to use some special names , Must be quoted .

Basic data types and reference data types

  • Basic data type :String Number Boolean Null Undefined

  • Reference data type :Object

** Basic data type data , Variables are stored directly, and their values .** Basic data types are stored directly in stack memory . Values are independent of each other , Modifying one variable does not affect the other variables .

** Reference data type data , A variable is a reference to a saved object ( Memory address ).** Objects are stored in heap memory . If multiple variables point to the same object , At this point, modify the properties of a variable , It affects other variables .

When you compare two variables , For basic data types , The comparison is the value , For reference data types, the comparison is address , The same address is the same

function (Function)

A function is also an object , It also has the function of ordinary objects ( Can have attributes )

Functions can encapsulate some code , You can call the function to execute the code when you need it

Use typeof Checking a function returns function

Create a function

The way functions are declared :

function  Function name ([ Shape parameter 1, Shape parameter 2... Shape parameter N]){
      
	 sentence ...  
}  

Function expression mode

var  Function name  = function([ Shape parameter 1, Shape parameter 2... Shape parameter N]){
      
	 sentence ...  
};  

Call function syntax : Function object ([ Actual parameters 1, Actual parameters 2... Actual parameters N]);

fun() sum() alert() Number() parseInt()

When we call a function , The code encapsulated in the function is executed in the order it was written

Immediate execution function

The function definition is finished , Immediately called , This function is called the immediate execution function

Executing a function immediately is often done only once

(function(a,b){
      
    console.log("a = "+a);  
    console.log("b = "+b);  
})(123,456); 

Traversing objects

for(var v in obj){
      
    document.write("property:name ="+v+"value="+obj[v]+"<br/>" );  
}  

Formal parameters and actual parameters

Shape parameter : Formal parameters

When defining a function , Can be in () Define one or more formal parameters in , Use between formal parameters , separate

Defining formal parameters is equivalent to declaring the corresponding variable in the function but not assigning values , Parameters are assigned only when called .

Actual parameters : The actual parameter

When you call a function , Can be in () Transfer argument , The passed argument is assigned to the corresponding formal parameter ,

When you call a function JS The parser doesn't check the type and number of arguments , You can pass values of any data type .

If the number of arguments is greater than the number of formal parameters , Extra arguments will not be assigned ,

If the number of arguments is less than the number of formal arguments , The formal parameters without corresponding arguments will be assigned values undefined

Return value , It's the result of function execution .

The return value of the function

Use return To set the return value of the function . grammar :return value ;

This value becomes the return value of the function , You can receive the return value through a variable

return The following code will not execute , Once implemented to return When the sentence is , The function will exit immediately .

The return value can be any data type , It can be a basic data type , It can also be an object , It can also be a function .

If return After not following the value , Or not return By default, the function returns undefined .

break、continue and return

break: Exit loop

continue: Skip this cycle

return: Exit function

Parameters , Function arguments can also be of any data type .

Method (method) You can set a function as a property of an object ,

When the property of an object is a function , We call this function the method of the object .

object . Method name ();

Function name ()

Properties and methods of functions

call() and apply()

These two methods are methods of function objects, which need to be called through function objects

When calling a function call() and apply() Will call the function to execute

Calling call() and apply() You can specify an object as the first parameter , At this point, the object will become the object of the function execution this.

  • call() Method can pass the arguments after the object in turn
  • apply() Method needs to encapsulate the arguments into an array and pass them uniformly
var obj = {
    };
fun.call(obj);
function fun(a,b) {
    
	console.log("a = "+a);
	console.log("b = "+b);
	//alert(this);
}
var obj = {
    
	name: "obj",
	sayName:function(){
    
	alert(this.name);
}
};
fun.call(obj,2,3);
fun.apply(obj,[2,3]);

arguments

When the function is called , The browser passes in two implicit parameters at a time :

  1. The context object of the function this
  2. The object that encapsulates the argument arguments

arguments Is a class array element , You can also manipulate data through indexes , You can also get the length

When the function is called , All the arguments we pass will be in arguments Kept in

arguments.length It can be used to get the length of arguments

Even if no formal parameters are defined , It can also be done through arguments To use arguments .

arguments[0]  Represents the first argument     
arguments[1]  Represents the second argument  ...

arguments There is a property in callee Represents the currently executed function object

this( The object that called the function )

this Is the context object of the function , Depending on how the function is called, it will be executed to different objects

  1. When called as a function ,this yes window
  2. When called as a method ,this It's the object that calls the method
  3. When called as a constructor ,this It's the new object
  4. Use call and apply Invocation time ,this It's the designated object
  5. In global scope this representative window

Scope (scope)

Scope is simply the scope of a variable .

stay JS There are two types of scopes in :

1. Global scope

  • Directly in script The code written in the tag runs in the global scope

  • The global scope is created when the page opens , Destroy when the page is closed .

  • There is a global object in the global scope window,window The object is provided by the browser ,

  • You can use it directly on the page , It represents the entire browser window .

  • Variables created in the global scope are treated as window Object's properties are saved

  • All functions created in the global scope are treated as window Object method save

  • Variables and functions created in the global scope are global , You can access... Anywhere on the page .

  • Variables in the global scope can also be accessed in the function scope .

  • Try not to create variables in the global

Variable declaration ahead of time :

Use var Keyword declared variables , Will be declared before all code is executed ( But no assignment ). But if you don't use var keyword , Then variables are not declared ahead of time .

2. Function scope

  • Function scope is the scope created when a function is executed , Each time the function is called, a new function scope is created .

  • Function scopes are created at function execution time , Destroy at the end of function execution .

  • Variables in the global scope can be accessed in the function scope . Variables created in function scope , Cannot access in the global .

  • When you use a variable in the scope of a function , It will first look for ,

    • If found, use , If not, go to the next level of scope to find ,
    • If found, use , If not, keep looking up , Up to global scope
    • If the global scope is still missing , May be an error ReferenceError
  • In global scope , Use var Keyword declared variables are declared before all code is executed , But no assignment .

  • So we can use variables before declaring them . But don't use var Variables declared by keywords are not declared ahead of time .

  • In the scope of a function , It also has this characteristic , Use var The variables declared by the keyword are declared before all the code of the function is executed ,

  • If not used var Keyword declaration variables , Then the variable becomes a global variable

  • To access global variables in a function, you can use window object

Function declaration ahead of time

In global scope , Use Function declaration creates a function (function fun(){}), Will be created before all code is executed , That is, we can call the function before the function declaration , But using function expressions (var fun = function(){}) The created function does not have this feature .

In the scope of a function , Functions created using function declarations , It will be created before the code in all functions is executed .

// Function declaration , Will be created in advance 
function fun(){
    
	console.log(" I am a fun function ");
}
// Function expression , Will not be created in advance 
function fun2(){
    
	console.log(" I am a fun2 function ");
}

this( Context object )

Every time the parser calls the function, it passes an implicit parameter to the function , The implicit parameter is this,this It points to an object , This object is called the context object of function execution ,

Depending on the way the function is called ,this Will point to different objects

  1. When called as a function ,this It's always window
  2. When called as a method ,this The object that calls the method
  3. When called as a constructor ,this Is the newly created object

Constructors

Use the factory method to create objects , Through this method, objects can be created in large quantities .

Existing problems : The constructor is used when creating objects Object, So the objects created are Object Type of , As a result, many different types of objects cannot be distinguished . So it's rarely used .

function createPerson(name , age ,gender){
     
	// Create a new object  
	var obj = new Object();
	// Add properties to the object 
	obj.name = name;
	obj.age = age;
	obj.gender = gender;
	obj.sayName = function(){
     
		alert(this.name);
	};
	// Return the new object to 
	return obj;
}

var obj2 = createPerson(" Pig eight quit ",28," male ");
var obj3 = createPerson(" Bones jing ",16," Woman ");
var obj4 = createPerson(" Spider essence ",18," Woman ");

Constructors are functions that are specifically used to create objects

Constructor is a normal function , There's no difference between creating a function and a normal function . The difference is that constructors are used to uppercase .

  • Ordinary function Call directly
  • Constructors Use new To call

Objects created by the same constructor , We call it a kind of object , Also call a constructor a class .

The object that will be created through a constructor , Called is an instance of this class .

Example :

function Person(name , age , gender){
      
    this.name = name;  
    this.age = age;  
    this.gender = gender;  
    this.sayName = function(){
      
        alert(this.name);  
    };  
}  

Constructor execution flow :

  1. Create a new object
  2. Set the new object to... In the function this, You can use this To reference a new object
  3. Execute the code in the function
  4. Return the new object to

instanceof Used to check whether an object is an instance of a class

grammar : object instanceof Constructors

If the object is an instance of the constructor , Then return to true, Otherwise return to false

Object Is the ancestor of all objects , So any object and Object do instanceof Will return to true

Enumerate properties in objects

for…in grammar :

for(var  Variable  in  object ){
      
  
}
// Every time it is executed , The name of an attribute in the object is assigned to the variable 

for…in The loop of the statement will execute many times , Several properties in the object are executed several times ,

Prototype (prototype)

After creating a function , The parser adds a number to the function by default prototype

prototype Property points to an object , This object is what we call a prototype object .

If the function is called as a normal function prototype It doesn't work

When a function is used as a constructor ,** The object it creates will have an implicit attribute pointing to the prototype object .** This implied property can be accessed through the object __proto__ To visit .

Prototype object is equivalent to a public area , All objects created by the same constructor usually have access to the same prototype object .

We can add common properties and methods to the prototype object , So we only need to add it once , So that all objects can be used .

Prototype objects are also objects , So it also has prototypes . When we access a property of an object or call a method of an object , It will first find in itself :

  • If you find it in yourself , Direct use .

  • If not found , Then go to the prototype object to find , If found, use ,

  • If not found , Then go to the prototype of the prototype to find

  • And so on . Until I find Object Until the prototype of ,Object There is no prototype , If it is still not found, return to undefined

When you create a constructor later , The properties and methods shared by these objects can be , Add uniformly to the prototype object of the constructor , This way, you don't have to add... To each object separately , It doesn't affect the global scope , Each object can have these methods and properties .

hasOwnProperty() This method can be used to check In the object itself Whether it contains an attribute

grammar : object .hasOwnProperty(“ Property name ”)

function MyClass(){
    
				
}
		
// towards MyClass Add a name attribute 
MyClass.prototype.name = " I'm the name in the prototype ";

var mc = new MyClass();
mc.age = 18;

//console.log(mc.name);// I'm the name in the prototype 

// Use in When checking whether an object contains an attribute , If not in the object but in the prototype , And will return to true
//console.log("name" in mc);//true

// You can use the hasOwnProperty() To check whether the object itself contains the property 
// Use this method only if the object itself contains properties , Will return true
//console.log(mc.hasOwnProperty("name"));//false
//console.log(mc.hasOwnProperty("age"));//true

toString Method

When we print an object directly on the page , Event is the output of the object toString() Return value of method

If we want to output objects without output [object Object], You can add a toString() Method

// modify Person Prototype toString
Person.prototype.toString = function(){
      
	return "Person[name="+this.name+",age="+this.age+",gender="+this.gender+"]";  
};  

Garbage collection (GC)

It's just like garbage will be produced when people live for a long time , Garbage will also be generated in the process of program running . After accumulating too much rubbish , Will cause the program to run too slow , So we need a recycling mechanism , To deal with garbage generated during program operation .

When an object does not have any variables or attributes to refer to it , At this point we will never be able to manipulate the object , At this time, the object is a garbage , Too many of these objects will take up a lot of memory space , Causes the program to run slowly , So this kind of garbage has to be cleaned .

stay JS There is an automatic garbage collection mechanism in , Will automatically destroy these garbage objects from memory , We don't need or can't do garbage collection , All we need to do is set objects that are no longer used null that will do .

Array (Array)

An array is also an object , It belongs to the built-in object , It's an object used to store data , and Object similar , But its storage efficiency is higher than that of ordinary objects

The contents of an array are called elements

Arrays use indexes (index) To manipulate elements

Index refers to 0 The starting integer

Array operation

Create array

// Use literals to create arrays :var  Array name  = []
var arr = [];
var arr = [10];// Create an array , There is only one element in the array 10
var arr1=[1,2,3,4,5,6];
// Create an array using a constructor :var  Array name  = new Array();
var arr2 = new Array();
var arr = new Array(10);// Create a length of 10 Array of 
var arr3 = new Array(1,2,3);

Adding elements to an array . grammar ; Array objects [ Indexes ] = value ;

arr[0] = 123;  
arr[1] = "hello";  

Add elements directly when creating an array . grammar :

 var arr = [ Elements 1, Elements 2.... Elements N]; 
 var arr = [123,"hello",true,null];  

Get and modify the length of the array : Use length Property to manipulate the length of an array .

To obtain the length of the Array .length

length Get the maximum index of the array +1

For continuous arrays ,length What we get is the number of elements in the array

Modify the length of an array Array .length = New length

If the revised length Larger than the original length , The extra part will be empty

If the revised length Less than the original length , The extra elements in the original array will be deleted

Add elements to the end of the array Array [ Array .length] = value ;

arr[arr.length]=70;

The elements in the array can be any data type :

// The elements in the array can be any data type 
arr = ["hello",1,true,null,undefined];

// It could be an object 
var obj = {
    name:" The Monkey King "};
arr[arr.length] = obj;
arr = [{
    name:" The Monkey King "},{
    name:" The sand monk "},{
    name:" Pig eight quit "}];

// It can also be a function 
arr = [function(){
    alert(1)},function(){
    alert(2)}];

// You can also put an array in the array , The following array is called two-dimensional array 
arr = [[1,2,3],[3,4,5],[5,6,7]];
console.log(arr[1]);

Array method

functionNamefunctionusage
push() Used to add one or more elements to the end of an array , And return the new length of the array Array .push( Elements 1, Elements 2, Elements N);
pop() To delete the last element of an array , And return the deleted element Array .pop();
unshift() Add one or more elements... To the beginning of the array , And returns the new length of the array Array .unshift( Elements 1, Elements 2, Elements N);
shift() Delete the first element of the array , And return the deleted element Array .shift();
reverse() Can be used to invert an array , It affects the original array
concat() You can connect two or more arrays , And return the new array , This method does not affect the original array

slice(sart,[end])

  You can intercept the specified elements from an array   
  This method does not affect the original array , Instead, encapsulate the intercepted content into a new array and return   
  Parameters :  
	1. Index at the start of the interception ( Including start position )  
	2. Intercept the index of the end position ( Does not include end position )  
		  The second parameter can be omitted , If you don't write it, it will be intercepted until the end   
	  Parameter can pass a negative value , If it's negative , Then count from back to front   
var arr = [" The Monkey King "," Pig eight quit "," The sand monk "," Tang's monk "," Bones jing "];
var result = arr.slice(1,4);//" Pig eight quit , The sand monk , Tang's monk "
result = arr.slice(1,-2);//" Pig eight quit , The sand monk "
result = arr.slice(1,-1);//" Pig eight quit , The sand monk , Tang's monk "
console.log(result);

splice()

  Can be used to delete the specified elements in the array , Will affect the original array , The specified element will be deleted from the original array , And return the deleted element as the return value 
	 This method encapsulates the deleted elements into a new array and returns   
  Parameters :  
	1. Delete the index at the start   
	2. Number of deletions   
	3. After three , They're all replacement elements , These elements will be inserted in front of the start position index   
var arr = [" The Monkey King ", " Pig eight quit ", " The sand monk ", " Tang's monk ", " Bones jing "];
var result =  arr.splice(1,1);// return :" Pig eight quit "
var result =  arr.splice(1,2);// return :" Pig eight quit , The sand monk "
console.log(result);

join([splitor])

 You can convert an array to a string 
 This method does not affect the original array , Instead, the converted string is used as the result 
 Parameters :
 You need a string as an argument , This string will be used as a connector to connect the elements in the array 
 If you do not specify a connector, the default is , As a connector 
var arr = [" The Monkey King "," Pig eight quit "," The sand monk "];
var result = arr.join("-");
console.log(result);//" The Monkey King - Pig eight quit - The sand monk "

sort()

You can sort the elements in an array , Will affect the original array , The default is Unicode Code to sort

Even for arrays of pure numbers , Use sort() Sorting time , I will also follow Unicode Code to sort . So when sorting numbers , You may get the wrong result .

We can specify the sorting rules by ourselves , Can be in sort() Add a callback function , To specify the collation , Two formal parameters need to be defined in the callback function . The browser will use the elements in the array as arguments to call the callback function , Which element to use to call... Is uncertain , But it's definitely in the array a It must be b in front .

  • The browser will determine the order of elements according to the return value of the callback function ,
    If it returns a value greater than 0 Value , Then the element will exchange positions
    If it returns a value less than 0 Value , Then the element position remains unchanged
    If you return one 0, The two elements are considered equal , Do not exchange positions

  • If you need to sort in ascending order , Then return to a-b
    If you need to sort in descending order , Then return to b-a

arr = [5,4,2,1,3,6,8,7];
arr.sort(function(a,b){
    
	// Ascending order  
	//return a-b; 
	  
	// Descending order  
	return b-a;  
});

Traversal array

Traversing an array is to get all the elements in the array to , Generally, we use it for Loop through the array

for(var i=0 ; i< Array .length ; i++){
      
    // Array [i]
}  

Use forEach() Method to traverse the array ( Are not compatible IE8)

 Array .forEach(function(value , index , obj){
      
  
});  

forEach() Method requires a callback function as an argument , There are several elements in the array , The callback function will be called several times ,

On every call , Will traverse to the information in the form of arguments passed in ,

We can define formal parameters to get this information :

  • value: The element being traversed

  • index: Traversing index of element

  • obj: Traversed object

var arr = [" The Monkey King "," Pig eight quit "," The sand monk "," Tang's monk "," Bones jing "];
arr.forEach(function(value , index , obj){
    
	console.log(value);
});
/*  The Monkey King   Pig eight quit   The sand monk   Tang's monk   Bones jing  */

Common classes and methods

Packaging

stay JS We are provided with ** Three packaging categories :**String()、Boolean()、Number()

Through these three wrapper classes, we can transform the data of basic data type into object

Example :

var num = new Number(2);  
var str = new String("hello");  
var bool = new Boolean(true); 

But don't do that in practice .

Methods and properties can only be added to objects , Cannot be added to base data type . When we call properties and methods on the values of some basic data types , The browser will temporarily use the wrapper class to convert it to an object , Then call the properties and methods of the object . After calling , And then convert it to the basic data type .

Date

The object of the date , stay JS Pass through Date Object to represent a time

Create objects :

  1. Create a current time object

     var d = new Date(); 
    
  2. Create a specified time object

    var d = new Date(" month / Japan / year   when : branch : second ");
    var d2 = new Date("4/14/2022 19:10:30");
    
name
getDate() What day is the current date object (1-31)
getDay() Returns the day of the week when the current date object is (0-6)
0 Sunday
1 Monday ...
getMonth() Returns the month of the current date object (0-11)
0 January 1 February ...
getFullYear() from Date Object returns the year... In four digits .
getHours() return Date The hour of the object (0 ~ 23).
getMinutes() return Date Object's minutes (0 ~ 59).
getSeconds() return Date The number of seconds of the object (0 ~ 59).
getMilliseconds() return Date Object's milliseconds (0 ~ 999).
getTime() Returns the timestamp of the current date object
Time stamp , Means from 1970 year 1 month 1 Japan 0 when 0 branch 0 second , The number of milliseconds up to now
The bottom layer of the computer saves time in the form of time stamp .
Date.now() You can get the timestamp of the current code execution

Math

Math Unlike other objects , It's not a constructor , It belongs to a tool class without creating objects , It encapsulates the properties and methods related to mathematical operations

Math Belongs to a tool class , It doesn't require us to create objects , It encapsulates constants and methods related to attribute operations

Math.abs() It can be used to calculate the absolute value of a number
Math.ceil() You can round up a number , Decimal places are automatically entered only if they have a value 1
Math.floor() A number can be rounded down , The decimal part will be rounded off
Math.round() You can round a number
Math.random() Can be used to generate a 0-1 Random number between
Generate a 0-x Random number between ,Math.round(Math.random()x)
Generate a x-y Random number between ,Math.round(Math.random()
(y-x)+x)
Math.max() You can get the maximum of multiple numbers
Math.min() You can get the minimum of many numbers
Math.pow(x,y) return x Of y The next power
Math.sqrt() Used to square a number

String related methods

String at the bottom, the string is saved in the form of character array :[“H”,“e”,“l”,“l”,“o”]

length: Can be used to get the length of the string

charAt(): Can return a character at a specified position in a string , Gets the specified character according to the index

charCodeAt(): Gets the character encoding of the character in the specified position (Unicode code ), Returns the encoding of a character

formCharCode(): You can get characters according to character encoding

concat(): Can be used to connect two or more strings , Function and + equally

indexof(): This method can retrieve whether a string contains the specified content , If the string contains that content , The index of its first occurrence is returned , If the specified content is not found , Then return to -1, You can specify the second parameter , Specify where to start searching (indexOF("h",1))

lastIndexOf(): The usage of this method and indexOf() equally , The difference is indexOf It's from the past to the future , and lastIndexOf It's back to front , You can also specify where to start searching

slice(): The specified content can be intercepted from the string , Does not affect the original string , Instead, the intercepted content is returned , Parameters :

  • first , Index of starting position ( Including start position )

  • the second , Index of end position ( Does not include end position )

    If you omit the second parameter , Will intercept all the following , You can also pass a negative number as an argument , Negative numbers will be calculated from behind

substring(): A string can be used to intercept , Sure slice() similar , Parameters :

  • first : Start intercepting the index of the location ( Including start position )

  • the second : Index of end position ( Does not include end position )

    The difference is that this method doesn't accept negative values as arguments , If you pass a negative value , It is used by default 0, And he automatically adjusts the position of parameters , If the second parameter is less than the first , Then automatically exchange

substr(): Used to intercept strings , Parameters :

  • Index at the start of the interception
  • Intercept length

split(): You can split a string into an array . Parameters : You need a string as an argument , The array will be split according to the string , If you pass an empty string as a parameter , Each character is split into an element in the array

toUpperCase(): Converts a string to uppercase and returns

toLowerCase(): Converts a string to lowercase and returns

Use ES6 New string method in

String.prototype.padStart(maxLength, fillString=’’) or **String.prototype.padEnd(maxLength, fillString=’’)** To fill the string ;

String and regular related methods

split()

You can split a string into an array

Method can pass a regular expression as a parameter , This method will split the string according to the regular expression

Can receive a regular expression , The array is split according to the regular expression

This method does not specify a global match , It's going to be all split up . Setting or not setting global variables is the same .

example : Split a string according to any letter

var str = "1a2b3c4d5e6f7";
var result = str.split(/[A-z]/);
console.log(result);//"1,2,3,4,5,6,7"

search()

You can search whether the string contains the specified content

If you find the specified content , The first occurrence of the index is returned , If there is no search return -1

It can take a regular expression as a parameter , The string is then retrieved from the regular expression

serach() Only the first , Even setting global matching doesn't work

str = "hello abc hello aec afc";
result = str.search(/abc/);
console.log(result);//6
result1 = str.search(/a[bed]c/);
console.log(result1);//6

match()

According to the regular expression , Extract the eligible content from a string

By default match Only the first content that meets the requirements will be found , Stop searching when you find it . We can set regular expressions to global matching patterns , This will match everything

You can set multiple matching patterns for a regular expression , And the order doesn't matter

match() It will encapsulate the matched contents into an array and return , Even if only one result is found

str = "1a2a3a4a5e6f7A8B9C";
result = str.match(/[A-z]/);//"a"
result = str.match(/[a-z]/ig);//"a,a,a,a,e,f,A,B,C"

replace()

You can replace the specified content in the string with the new content . Parameters :

Regular expressions

Regular expressions are used to define some rules for Strings , The program can judge whether a string conforms to the rules according to these rules , You can also extract the content of a string that conforms to the rules .

Create regular expression

(1) Use the constructor method :var Variable = new RegExp(" Regular expressions "," Matching mode ");【 More flexible 】

var reg = new RegExp("a");
var reg1 = new RegExp("a","i");
console.log(reg);// Output :/a/

(2) Use literal methods :var Variable = / Regular expressions / Matching mode 【 It's simpler 】

var reg = /a/i;//a It's a regular expression ,i It's a matching pattern 

Use typeof Check regular objects , Returns the object

Regular expression methods :test(). This method can be used to check whether a string conforms to the regular expression rules , If yes, return true, Otherwise return to false

var reg = new RegExp("a");// This regular expression can be used to check whether a string contains a
console.log(reg.test("ac"));// Output :true
console.log(reg.test("bgds"));// Output :false
console.log(reg.test("Abgds"));// Output :false

You can pass a matching pattern as the second parameter in the constructor :i【 Ignore case 】、g【 Global match pattern 】

var reg = new RegExp("a","i");
console.log(reg.test("Abgds"));//true
| or
[] or
[^ ] except
reg = /a|b|c|d|e|f|g/;
reg = /[ab]/;
/* [ab]==a|b */

[a-z] Lowercase letters ( It's fine too [e-i])

[A-Z] Capital

[A-z] Any letter , But there are others ASCII In this

[0-9] Arbitrary number

example 1: Check a string for abc or adc or aec

reg = /a[bde]c/;
console.log(reg.test("aec"));//true

quantifiers

You can set the number of times a content appears through quantifiers , The quantifier only works on one of the contents in front of it

  • {n} Just in time n Time 【/a{3}/】
  • {m,n} appear m-n Time 【/ab{1,3}c/】
  • {m,} m More than once 【/ab{3,}c/】
  • + At least one , amount to {1,}【/ab+c/】
  • * 0 One or more , amount to {0,}【/ab*c/】
  • ? 0 Or 1 individual , amount to {0,1}【/ab?c/】

Boundary expression ( Not in java of use ,javaScript of use )

  • ^: Regular start
  • $: Regular end : Note that the last one before the end is the end match
reg = /^a/; // Match the beginning of a
reg = /a$/; // Match ending a

If you use both in regular expressions ^ $ Then the string must conform to the regular expression

reg = /^a$/;

Check whether a string contains .(. For any character )

Use... In regular expressions \ As an escape word :

  • \. To express .
  • \\ Express \

Be careful : When using constructors , Because its parameter is a string , and \ Is an escape character in a string , If you want to use \ You need to use \\ Instead of

  • \w Any letter 、 Numbers 、_、[A-z0-9_]
  • \W In addition to the letter 、 Numbers 、_、[^A-z0-9_]
  • \d Any number [0-9]
  • \D In addition to digital [^0-9]
  • \s Space
  • \S Except for the space
  • \b Word boundaries
  • \B Except for word boundaries

example : Remove the space in the string . Removing spaces is using "" To replace spaces

var str = " hel lo ";
str = str.replace(/\s/gi,"" );// Remove all spaces 
console.log(str);//hello
str = str.replace(/^\s*/, "");// Remove the leading space 
str = str.replace(/\s*$/, "");// Remove the space at the end 
str = str.replace(/^\s*|\s*$/g,"");// Remove the spaces at the beginning and end .hel lo

copyright notice
author[Chen Chen is trying],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/04/202204290808465437.html

Random recommended