1. JavaScript is introduced

JavaScript is the prefix Java, but the relationship between Java and JavaScript is like the relationship between a wife and a wife-cake.

JavaScript was first introduced by netscape with Netscape2.0. JavaScript’s official name is “ECMAScript”. This standard was developed and maintained by the organization ECMA, or “js” for short. Used to add interactive behavior to HTML pages.

JavaScript is an object – and event-driven interpretive scripting language that is embedded directly into HTML pages and executed by the browser without precompilation.

1.1 JS features

It can be written using any text editing tool, and you only need a browser to execute the program

  • Explain execution: Execute line by line without prior compilation
  • Object-based: A large number of ready-made objects are built in
  • Suitable for:
    • Client data calculation
    • Verify client form validity
    • Triggering of a browser event
    • Web page special display effect making

1.2 JS composition

  • ECMAScript: Defines standards for core syntax, keywords, operators, data types, etc

  • DOM: Document object model that treats all nodes of an HTM L page as objects one by one. More hierarchical management of each

One node.

  • BOM: Browser object model that accesses and manipulates browser Windows.

    Using the BOM, developers can move Windows, change text in the status bar, and perform other actions that are not directly related to the content of the page. What makes BOM unique, and often suspect, is that it is just a part of JavaScript without any relevance. Popup new browser window move, close, and resize the browser window location object that provides Web browser details Screen object that provides user screen resolution details Support for cookies IE extended BOM to include ActiveXObject class, The Ajax local refresh technique can be implemented by instantiating ActiveX objects through JavaScriptCopy the code

2. HTM L combined with javaScr IPT

2.1. Inline scripts

    1. Click the button (trigger)
    1. Frame (Specific operation)
<button onclick="Alert (' popbox test ')" >Point me</button>
Copy the code

2.2. Internal scripts

    1. Use the script
    1. The standard is between head and body (neck position), but you can just write it inside the HTM L file, no matter where
<html>Outside,<p></p>Inside, either way.<body >
<script >
alert("Bounced" );
</script>
</body>
Copy the code

2.3. External scripts

    1. Create a directory js under the project root
    1. Create a file in the js directory with the suffix.js
    1. In the HTM L page
<script src="js/xx.js"></script>
Copy the code

The priority of the above three ways of using the script, who is on, who executes first. Because it’s interpreted language.

3. Use of JavaScript

3.1 variable

Because JS is a weakly typed language, when defining variables, all data types are var

  • Declare variables: var x; var x,y;

  • Numeric types: number: Does not distinguish between integer and floating point values. All numbers are stored in 64-bit floating point format, similar to the double format

  • String: string: surrounded by single or double quotation marks,var aa=” Welcome to \ “JavaScript world “;

  • Boolean type: only two values: true and false also represent 1 and 0. In practice, true=1 and false=0

3.1.1 Automatic Type conversion

  • Number + String: Numbers are converted to the string 10+ ‘a’ -> 10A

  • Numbers + Boolean values: true converts to 1, false converts to 0, true+5- >6

  • String + Boolean: Converts a Boolean to the string true or false. True + ‘a’ – > truea

  • Boolean + Boolean: Converts a Boolean value to a value of 1 or 0, true+true->2

3.1.2 Data type conversion function

  • ParseInt: force conversion to an integer

If the conversion is not possible, NaN is returned. (The NaN attribute is a special value representing a non-numeric value. This property is used to indicate that a value is not a number

For example: parseInt(“6.32”)=6 parseFloat: cast to float or return NaN if not. Example: parseFloat(“6.32”)=6.32

  • Typeof: numerical current query types, return the string/number/Boolean/object

For example: typeof (” test “+ 3) = =” string”

3.1.3 null and undefined

  • null

Stands for “no value” or “no object” in a program. You can clear the contents of a variable by assigning it the value NULL

  • undefined

Variables are declared but never assigned or object attributes do not exist

3.1.4 Arithmetic operations

Add (+), subtract (-), multiply (*), divide (/), remainder (%)

  • – can be a minus or a minus sign, for example, x = -y

  • + can be used for addition or concatenation of strings

Increasing (++), decreasing (–)

I ++ is the same thing as I = I +1 I -- is the same thing as I = I -1Copy the code

3.1.5 Relational operation

  • Strictly equal: ===

    Same type and same valueCopy the code
  • Non-strict equality:! = =

var	a="10";
var	b=10;
if(a==b)
alert("equal");
if(a===b)
alert("same");
Copy the code

3.1.6 Logical Operation

Logic is not (!) , logic and (&), logical or (| |)

The operands of logical operations are Boolean expressions

3.1.7 Control Statements

if(relational expression) {// Block 1
}else{
// Block 2
}

if(expression1) {/ / statements 1;
}else	if(expression2) {
/ / statements 2;
}else	if(expression3) {
/ /statements3;
}else{
/ / statement 4;
}
 
switch(expression){case1:
/ / statements 1;
break;
case2:
/ / statements 2;
break;
default:
/ / statement 4;
}


for(vari =1; i <=5; i++) { alert(i); }while(Condition) {/ / statements 1;...}Copy the code

3.2 Common String API

  • Length: Gets the length of the string (the number of characters in the string) property, without braces
var str="hello";
console.log(str.lengt	);
Copy the code
  • ToUpperCase /toLowerCase: Transfer case
var name= AngierSun";
console.log("A capital" +name.toUpperCase( ));
console.log("lowercase"+name.toLowerCase( ));
Copy the code
  • CharAt (subscript) : Returns the character on a subscript
var str1="Javascript Web Tutorial"
var str2=str1.charAt( 2);// the character on the subscript 12
console.log(st2);/ / teach
var str3=str1.charCodeAt( 12);
console.log(str3);//25945 :(Chinese character "jiao" in unicode encoding)
Copy the code
  • Indexof (character) : Searches for the first occurrence of a character in a string

  • LastIndexof (Character) : Finds the index of the last occurrence of a character in a string

var str1="Javascript Web Tutorial" ;
var str2=str1.indexOf( " a");console.log( st r 2);/ /1, the subscript of the first occurrence of a character in STR1var str3=str1.lastIndexOf("a");// 3, the last occurrence of the a character in str1
console.log(str3) ;
Copy the code
  • Substring: Intercepts part of a string(the end is not included)
var str1="ab defgh";
var str2=str1.substring(2.4);console.log(str2);/ /From CD,2Start (contain),4End (not included)Copy the code
  • Replace (old, new) : Replaces old characters in a string with new characters
var str1="abcde" ;
var str2=str1.replace("cd" ,"XXX");console.log(str2);//bXXXe, replace CD in st r 1 with XXX
Copy the code
  • Split: A string is split into N smaller strings, so an array type is returned
var str1="One, two, three, four, five";
var arr=str1.split( ","); / Split STR by comma into N parts, so the result must be an array structureconsole.log("Divided into:" +arr.length+"份");
console.log("The third is:"+arr2) ;
Copy the code

3.3 an array

3.3.1 Creating an Array

var arr1=new Array(a);Copy the code

3.3.2 Three ways to initialize an array

/ / the first
var arr1=newArray( );
arr1[0] =110;
arr1[1] =119;
arr1[2] =120;
/ / the second
var arr1=newArray( 10." a" , true);/ / the third kind
var arr1=[ 10." a" ,true];for(vari=0; i<arr1. ength; i++) {console.log(arr1[i]);
}
Copy the code

3.3.3 Common methods of arrays

  • Tostring () : Converts an array to a string
 
var arr=[ 1.2.3.4];console.log( "Type:"+typeof(arr));
var str=arrtoString();	// Convert an array to a string
console.log(str+", type:"+typeof(str));
Copy the code
  • Join: Joins each element in an array into a new string using a join symbol.
var arr=[ 1.2.3.4];var str=arr.join("-");	// Concatenate each element of the array with - to form a new string
console.log(str+", type:"+typeof(str));
Copy the code
  • Concat (new element) : Concatenates the original array with the new element, unchanged.
var arr	= 1.2.3.4];var arrnew=arr.concat(5.6);// Add a new element to the end of the arR array to form a new array, but the original array is unchanged
console.log(arrnew+", type:"+typeof (arrnew));
console.log( "Original array:"+arr) ;
Copy the code
  • Slice: To extract a portion of an array to form a new array.

1,2,3,4,5 slice(2,4

var arr=[ 'a'.'b'.'c'.'d'.'e'.'f'.'g'.'h'];var arrnew=arr.slice(2.4); // Start with 2 (included) and end with 4 (not included)
console.log(arrnew);//cd
Copy the code
  • Reverse () : Reverse array (in reverse order)
var arr=[31.12.111.444];console.log(arr.toString( ));
arr.reverse( );// Invert the elements of the array
console.log(arr.toString( ));
Copy the code
  • Sort () : array sort
Arr.sort () character sort vararr= [31.12.111.444]; arr.sor ( ) ;// Sort characters (not by literal size)
console.log(arr); Arr.sort (func) Sort valuesvar arr=[ 31.12.111.444];
arr.sort(laosun);// Sort by number (literal size)
console.log(arr);

// Define the sort function
function laosun(a,b) {
return	a- b;
}
Copy the code

3.4 Math objects

The Math object is used to perform mathematical tasks. There is no constructor for Math(), which does not need to be created. Using Math directly as an object calls all of its properties and methods

// Return a random number between 0 and 9
var i=Math.random()*10;
var j=Math.floor (i);
console.log(j);
Copy the code

3.5 Number object

Number.fixed(2); Comes with rounding skills

var n = new Number( 12.345 );
var n1 = n.toFixed(2); // 12.35, fixed two decimal places, rounded off the third decimal place
console.log( n1 );

var x = new Number( 12.3 );
var n2 = x.toFixed(2); // 12.30, fixed two decimal digits, 0 to complete
console.log( n2 );
Copy the code

3.6 Regular Expressions

Powerful tool to perform pattern matching on strings

var reg1 = / ^ \ d {3, 6} $/;	// Match 3-6 pure numbers

var reg2 = new RegExp(" ^ \ \ d {3.6} $");1 / / way
var age="18";// Judge: 1- 3 pure digits
var reg=/ ^ \ d {1, 3} $/;// Start with / ^, write the re in the middle, and end with $/
var b=reg.test(age);// Verify that age matches r eg
if(b==true) {console.log("Verified!"); }else{
console.log("Formatting error"); }2 / / way
var name="abc123";// A string of 5 to 8 characters consisting of uppercase and lowercase letters and digits (special characters cannot appear)
var reg	=newRegExp("^ [a zA - Z0-9] {5, 8} $");// Start with ^, write the re in the middle, and end with $
if(reg.test(name)){
console.log("Verified");
}else{
console.log( "Formatting error");
}
Copy the code

3.7 Date Objects

var time=new Date(a);console.log(time);// Tue Jul 14 2020 11:09:46 GMT+0800
var year=time.getFullYear ( ) ;/ / year
var month=time.getMonth( )+1;// The month starts at 0 and ends at 11, so it's customary to +1
varday=time.getDate( );/ / number
varhour=time.getHours( )	What time / /
varmm=t i me. getMinut es( );/ / minute
vars=time.getSeconds( );/ / SEC.varms= ime.getMilliseconds( ); / ms,1000Ms =1Second vartimestr = year +"Year" +mont h+"Month" +day +" 号	" +hour +"Point" +mm+"Points" +s+"Seconds" +ms +"Ms" ;
console.log(timestr) ;
Copy the code

3.8 the function

Function function name (parameter list) {// function body return return value; }

Functions are not executed immediately after they are declared; they are called when we need them. Note:

  • Parameter: Must not have data types
  • The semicolon is used to separate executable JavaScript statements. Since the function declaration is not an executable statement, it does not end with a semicolon.

3.8.1 No Returned Value

function qiuhe(a,b){
var he=	a+b;
console.log( "Sum of two numbers:"+he) ;
}
qiuhe(3.4);
Copy the code

3.8.2 There are return values

function qiuhe(a,b){
var he=a+b;
return "Sum of two numbers:"+he;
}

var s=qiuhe(3.4);
console.log(s);
Copy the code

3.8.3 Parameter Object

Inside the function, the properties of the argument list are called

functon func(a,b,c){
console. og(arguments.length);// Get the number of arguments
console.log(arguments[1]);// Get the argument with subscript 1
}
Copy the code

3.8.4 Constructors

Functions can also be defined using the built-in JavaScript Function constructor (Function())

var myFunction=new Function("a"." b"."return a*b");
var x=my Function(4.3);
console.log(x) ;
Copy the code

Note: The above function ends with a semicolon because it is an execution statement.

3.8.5 Anonymous Functions

A function without a name

var fn=function(a,b){// A function without a name should be received with a variable
return	a*10+b;
};
console.log(fn(3.4));
Copy the code

Global functions

-isNaN: checks whether the parameter is a non-numeric value

console.log(isNaN(123));// number false
console.log(isNaN("hello"));// Non-numeric, true
console.log(isNaN(4-1));// number false
console.log(isNaN(123));// number false
console.log(isNaN(-10));// number false
console.log(isNaN("123"));// number false
console.log(isNaN("1a23"));// Non-numeric, true
Copy the code

-eval: converts an operation in a string

var	str="1 + 3";
console.log(str);// 1+3, + is regarded as a character character, no addition function
console.log(eval(str));	// Make the operation symbol in the string work
Copy the code

– encodeURI and decodeURI

var name="111";
console.log("Before transcoding:"+name);

name=encodeURI(name);
console.log("After transcoding:"+name);

name=decodeURI(name);
console.log("After decoding:"+name);
Copy the code

# # # 3.8.7 closures

  • 1. The concept of closure: refers to a function that has access to variables in the scope of another function, usually including another function in one function.

  • 2. Closures are used to access variables inside functions and keep functions in the environment, so they will not be garbage collected.

Simply put: declare a closed environment within the local scope of a function that will not be detected by garbage collection. Ensure the security and uniqueness of data

To understand closures, you need to first understand what are global variables and what are local variables

a=10;// Global variables can be declared without var
function test1(){
b=20;// Global variables that do not apply to var declarations
var c=30;// Declare with var, and inside the function. Such variables are called local variables and are valid only within the function they declare
console.log(c);
}
function test2(){
console.log(c);	//c is not defined (c is not defined)
}
test1();
test2();
Copy the code

Anyone can access count, so the count variable is not safe because it is a global variable. How to be safe? Declare count as the local variable A

function test1(){
var count=0;	// Local variables
return	count++;// External access to the count variable can only be returned by return, and typeA} test1 (); test1(); test1();console.log(test1());// Every time a method is called, the variable is first restored to 0
Copy the code

The result is always 0, because every time test1() is called, the first line of the method body is restored, regardless of what the value was. Test1 () supports nested functions. Test1 () supports nested functions

function test1(){
var count=0;// Local variables
function jia(){
return	count++;
}
jia();
return	count;
}

test1();
test1();
test1();

console.log(test1());// Every time a method is called, the variable is first restored to 0
Copy the code

It would be nice if you just called jia() from test1() each time. Ok, close the package to help you solve this problem!

function test1(){
var count=0;	// Local variables
function jia(){
return	count+=1;
}
return	jia;
}

var	fn=test1();// fn=>functionjia(){return count+=1; }
fn();
fn();
console.log(fn());	// Every time a method is called, the variable is first restored to 0
Copy the code

Closures are a mechanism for protecting private variables from outside interference by forming private scopes during function execution. Intuitively speaking is to form an undestroyed stack environment

  • Closure advantages: Easy to call local variables declared in the context of the logic is tight, you can create a function within a function, avoiding the problem of passing parameters

  • Disadvantages of closures: Because of the use of closures, functions can not be destroyed after execution and remain in memory, if the use of a large number of closures will cause memory leaks, memory consumption

##3.9 Popbox output

  • Alert (“hello, 111”);

  • Console log output console.log(” Google Browser press F12 to enter console “);

  • Document. write(” H2 I love you China H2 “); Output the H2 element to the body

  • Confirm box (” Are you sure you want to delete it?” );


var b=confirm("Are you sure?");
if(b){
document.write(	"

Deleted successfully!

"
); }else{ document.write( "

You cancelled the operation

"
); } // Input box prompt(" Please enter name: "); var name=prompt("Please enter your name:"); document.write( "

Name:"

+name+! "" " ); Copy the code