JavaScript notes

Venusoooooo 2021-01-24 15:59:12
javascript notes


JavaScript Notes

1. brief introduction

1. Language description

JavaScript It's a cross platform 、 Object oriented weakly typed dynamic scripting language

JavaScript It's a prototype 、 Function first language

JavaScript It is a multi-paradigm language , It supports object-oriented programming 、 Imperative programming and functional programming

It was originally created to “ Make the web page more vivid ”

Scripts are provided and executed in plain text ; They don't need special preparation , Compile and run

2. The origin of the name

JavaScript Prototype in 1995 year 4 month Be in NetScape Brandon at work • Ike (Brendan Eich ; Moizlla/Brave Browser founder ) create

At the beginning of its birth, it was called “LiveScript ”, Later, because of the promotion, the hot words of programming at that time “Java”, So it was renamed JavaScript

JavaScript and Java Except for some grammatical similarities , There is no connection between the application fields and the subsequent development of the two

Language Standardization :

1997 year 6 month ,ECMA(European Computer Manufacturers Association Later renamed Ecma International) With JavaScript For the language foundation

Formulated the ECMAScript Standard specification ECMA-262, JavaScript Also become ECMAScript One of the most famous realizations

3. Other introductions

With JavaScript Continuous development ,JavaScript Not only in the browser , It can also be executed on the server (node.js), It can even be carried anywhere JavaScript In the device of the engine

Embedded in the browser JavaScript engine , Sometimes called “JavaScript virtual machine ”

Different engines have different “ Code name ”

  • V8 ———— Chrome and Opera Medium JavaScript engine
  • SpiderMonkey ———— Firefox Medium JavaScript engine
  • Chakra ———— IE Medium JavaScript engine
  • ChakraCore ———— Microsoft Edge Medium JavaScript engine
  • Nitro and SquirrelFish ———— Safari Medium JavaScript engine

How the engine works ?

​ The engine is complicated , But the fundamentals are simple

  1. engine ( If it's a browser , Then the engine is embedded in it ) Read (“ analysis ”) Script
  2. then , The engine transforms the script into (“ compile ”) For machine language
  3. then , Fast execution of machine code
  • The engine optimizes every stage of the process ; It can even monitor compiled scripts as they run

    Analyze the data flowing through the script , And further optimize the machine code according to the obtained information

In the browser JavaScript What can be done ?

modern JavaScript It's a kind of “ Safe ” programing language ;

It does not provide for memory or CPU Bottom level access to ; Because it was originally created for browsers , You don't need these functions

In the browser JavaScript Can do with webpage operation 、 User interaction and Web Everything about servers

  • Add a new html , Modify the existing content and style of the web page
  • Respond to user behavior , Respond to mouse clicks , The movement of the pointer , The movement of keys
  • Send network requests to remote servers , Download and upload files (AJAX and COMT technology )
  • Get or set cookie , Provide questions or send messages to visitors
  • Remember the client's data (“ The local store ”)

In the browser JavaScript Nothing to do ?

For users ( Information ) Security , In the browser JavaScript My ability is limited

The purpose is to prevent malicious web pages from obtaining users' private information or damaging users' data

  • In the web page JavaScript Cannot read 、 Write 、 Copy and execute any file on the hard disk ; It doesn't have direct access to the operating system functions

    Modern browsers allow JavaScript Do some file related operations , But this operation is limited

    Only if the user makes a specific behavior ,JavaScript To operate this file

    for example : The user puts the file ” Drag and drop “ Go to browser Or by <input> The tag selects the file

  • Different tabs / Windows usually don't know each other

    occasionally , There will also be some connections

    for example : A label goes through JavaScript Another tab that opens ; But even in this case

    ​ If two tabs don't open the same website (URL China Agreement 、 Any website with different domain name or port ), They can't communicate with each other

    ​ That's what's called “ The same-origin policy ” ( The same origin policy only applies to scripts )

    ​ In order to solve “ The same-origin policy ” problem , Both tags must contain some specific JavaScript Code , And all allow data exchange

  • JavaScript Can easily communicate with the current server through the Internet ; But from other sites / The ability to receive data in the domain's servers is weakened

    Even though you can , But you need an explicit protocol from the remote server ( stay HTTP header in )

    If out of browser ( For example, on the server ) Use JavaScript, There is no such limitation

    Modern browsers also allow you to install plug-ins that may require extended permissions / Expand

    JavaScript “ The upper ” Language

    As development advances ,JavaScript It's not enough grammar for everyone , So there are a lot of new languages

    Before these languages are executed in the browser , Will be compile ( conversion ) become JavaScript

    Such languages as :CoffeeScript 、TypeScript 、Flow 、Dart 、Brython etc.

2. grammar

1. JavaScript Introduction mode

1. Embedded

stay html Any number of... Can be placed in the document JavaScript Script

  1. <head> Medium JavaScript Script

    <!DOCTYPE html>
    <html>
    <head>
    <script>
    function myFunction(){
    document.getElementById("demo").innerHTML=" The paragraph was changed ";
    }
    </script>
    </head>
    <body>
    <h1> A web page </h1>
    <p id="demo"> A paragraph </p>
    <button type="button" onclick="myFunction()"> Have a try </button>
    </body>
    </html>
    
  2. <body> Medium JavaScript Script

    <!DOCTYPE html>
    <html>
    <head>
    <title>body Medium JavaScript Script </title>
    <style type="text/css">
    #Oliva{
    color: blue;
    font-family: serif;
    font-style: italic;
    }
    </style>
    </head>
    <body>
    <p id="Oliva">Oliva is a beautiful words!</p>
    <script>
    document.getElementById("Oliva").style.color= "gray";
    document.getElementById("Oliva").style.fontFamily= "san-serif";
    document.getElementById("Oliva").style.fontStyle= "oblique";
    /* Be careful italic And oblique The difference between ;italic Indicates that the text style is italicized , and oblique It's an artificially slanted font */
    /* Usually, the script is placed in <body> The bottom of the element */
    </script>
    </body>
    </html>
    

2. Outreach

Of course, it can also be done through the complete URL Or refer to an external script relative to the path of the current page

<script src=“xxxxx”></script> Put it in head and body Fine

  1. complete URL Link script

    <!DOCTYPE html>
    <html>
    <head>
    <title> An ellipse </title>
    <style type="text/css">
    #oval{
    width= 200px;
    height= 100px;
    border-width: 1px;
    border-style: groove;
    border-color: rgb(129,60,133);
    border-radius: 40px/20px;
    }
    </style>
    </head>
    <body>
    <div id="oval">Draw an oval</div>
    <script src="https://github.com/Kuiperabxy/libertas/tree/main/oval.js">
    /* Through the complete URL To link to the script */
    </script>
    </body>
    </html>
    
  2. Import the script in the specified folder on the current website

    <script src="/Kuiperabxy/libertas/tree/main/oval.js">
    /* Introduce the script of the specified folder of the current website */</script>
    
  3. Introduce a script in the same folder as the current page

     <div id="oval">Draw an oval</div>
    <script src="oval.js"> /* Introduce the script of the same folder in the current website */</script>
    <!-- If you need to introduce multiple JavaScript file Multiple required script label -->
    

    The advantages of outreach :

    • Separated html and JavaScript Code
    • send html and JavaScript Easier to read and load
    • Cached JavaScript Files speed up page loading

2. JavaScript Output mode

JavaScript No built-in print or display functions are provided

JavaScript Be able to... In different ways “ Show ” data :

  • Use window.alert( ) Write warning box

  • Use document.write( ) write in html Output ( For testing only )

  • Use innerHTML write in html Elements ( change html Elemental innerHTML Property is in html Common ways to display data in )

  • Use console.log( ) Write to browser console

    <!DOCTYPE html>
    <html>
    <head>
    <title>JavaScript Different output modes </title>
    </head>
    <body>
    <script>window.alert(2+8);</script>
    <script>document.write(2+8);</script>
    <p> change html Elements </p>
    <p id="nua"> The change is here </p>
    <script>
    document.getElemntById("nua").innerHTML="SiChuan University is best university in SiChuan!"
    </script>
    <script>console.log(2+8);</script>
    </body>
    </html>
    

3. JavaScript Basic grammar

A computer program is a computer “ perform ” A series of “ Instructions ”

In programming languages , These programs “ Instructions “ It's called a statement

JavaScript Program It's a series of programming statements

1. JavaScript Sentence structure

value 、 Operator 、 expression 、 key word and notes

2. JavaScript value

JavaScript Statement defines two types of values : Mix value ( Literal value literal ) and A variable's value ( Variable )

A string is a literal quantity ; Surround with double or single quotation marks

Constant is also a kind of literal quantity

Javascript Variable

In programming languages , A variable is Storage Container for data values

for example : var x = 7; var y = 10;(x Storage 7 ; y Storage 10)

It's like algebra

for example : var total = x + y; ( total It's also a variable , Express in an algebraic way )

3. JavaScript expression

Expressions are values 、 A combination of variables and operators , The result is the value of

Such as :6*10“Bill” + “ ” + “Gates”

4. JavaScript key word

JavaScript A sentence is often represented by a keyword identification executable JavaScript action

  • attach :JavaScript key word

    key word describe
    break End switch loop
    continue Jump out of the loop and start at the top
    debugger Stop executing JavaScript, And call the debug function ( If available )
    do……while Execute statement block , And repeatedly execute the code block when the condition is true
    for Mark the blocks of statements that need to be executed , If the condition is true
    function Declare functions
    if……else Mark the blocks of statements that need to be executed , According to a certain condition
    return Exit function
    try……catch Implement error handling for statement blocks
    var Declare variables

5. JavaScript Code block

​ The purpose of the code block is Define the statements to be executed together

​ The contents of a code block usually need to be indented with spaces , enhance readability

Be careful :

  1. Semicolons separate JavaScript sentence , Be sure to add.
  2. to JavaScript Statement to enhance readability ( Next to the operator )
  3. For best readability , Code line characters are often controlled in 80 Within a

6. JavaScript notes

Not all JavaScript sentence All be “ perform ”

Double slash // ( A single ) perhaps Be situated between / / ( Multiple lines ) The code between is treated as a comment

7. JavaScript identifier

The identifier is the name ,JavaScript Identifiers are case sensitive And Have uniqueness

stay JavaScript in , The identifier is used for Named variable ( And key words 、 function 、 label )

Most programming languages , The rules for legal names are almost the same

The rules : The first character must be Letter 、 Underline (__) perhaps Dollar symbol ( $)

​ Strings can be letters 、 Numbers 、 Underline or dollar sign

​ A string of characters with Hump case (eg: getElementById)

8. JavaScript Character set

JavaScript Use Unicode ( unicode ) Character set

Unicode Covering the world Almost all the characters 、 Punctuation and symbols

9. JavaScript Operator

Please refer to the website for details :https://www.w3school.com.cn/js/js_operators.asp

10. JavaScript data type

Data types are concrete value types

  • 5 Kind of May contain value data types
    • A string value (string)
    • Numerical value (number)
    • Boolean value (boolean)
    • object (object)
    • function ( function)
  • 3 Kind of object type
    • object (object)
    • date (date)
    • Array (array)
  • 2 Kind of Cannot contain type of value
    • null
    • undefined

JavaScript Have dynamic types , It means that the same variable can be used for different types ; for example : var x = 10; var x = “bill”

stay JavaScript in , Variables without values , Its value is undefined , The type is also undefined; That is, any variable can have its value set to undefined To empty

Null value (“ ”) and undefined It's not the same thing , Empty strings have both values and types

null The value of is null , The data type is object ; Of course, you can also set the value to null Empty objects

stay JavaScript in , Arrays are also objects for example :typeof [3,5,6,8] The return is object Instead of array

Raw data : Raw data value is a single simple data value without additional properties and methods

for example :string 、 number 、boolean 、undefined

object 、 function Belong to Complex data

11. JavaScript function

JavaScript Functions are blocks of code designed to perform specific tasks ; It's usually defined once , Can be called many times

JavaScript function Will be executed when a code calls it

Grammatical structure

function myFuncationName ( param1 , param2 , param3 ) {

Code to perform a specific task ;

}

myFuncationName Is the function name , Use... When called

param When you call a function , The real value received by the function

In the function , param It's a local variable , That is, it can only be accessed inside the function ; Create... At the beginning of the function , Deleted on completion

In other programming languages , Function approximation Program ( Procedure) or Subroutines (Subroutine

Function call

  • When the event occurs ( When the user clicks the button )
  • When JavaScript When the code is called
  • automatic ( Self calling )

The function returns

When JavaScript arrive return When the sentence is , Function stops executing

Usually, the function calculates the return value and returns it to the caller

12. JavaScript object

In real life , The car is an object

Cars have things like Vehicle weight and Color Equal attribute ; There are also start-up and stop it Other methods

All cars have the same characteristics attribute , but Property value It's different from car to car

All cars have the same Method , But methods are executed at different times

Objects are also variables ; But objects contain a lot of values ( Object properties ); Objects cannot be compared

Object properties to name : value The right way to write

JavaScript object Is the named value ( Object properties ) The container of

for example :var car = {type: "porsche", model: "911", color: "white"};

The method of an object is an action performed on the object

Methods to Function definition Stored in attributes ; namely Methods are stored as attributes function

for example : var person = {

firstName: “Bill” ,

lastName: “Gates” ,

fullName: function( ) {

return this.firstName + “ ” + this.lastName ;

}

}

this key word

In the definition of a function ,this quote Of this function “ The owner ”, The current object ; In the above example ,this.firstName Equivalent to person.firstName;

Access object properties

There are two ways to access the properties of an object

  1. objectName.propertyName namely Object name : Property name
  2. objectName[“ propertyName ”] namely Object name [“ Property name ” ]

Access object methods

objectName.methodName( ) namely Object name . Method name ( )

13. JavaScript event

html The incident happened in html Element “ Thing ”,JavaScript can “ Answer ” These events

html Events can be browser or Something users do , Usually when something happens , Users will want to do something

adopt JavaScript Code , Can be in html Element to add an event handler

Event handler Can be used for Handle 、 Verify user input 、 User actions and browser actions

  • What you should do every time a page loads
  • What to do when the page is closed
  • Actions that should be performed when a user clicks a button
  • What should be verified when the user enters data

Code format ( single / Double quotation marks are OK )

< element event= “ some JavaScript">

for example :

change id=“demo” The content of the element

<button onclick = ‘document.getElementById(“demo”).innerHTML = Date( )'> Now the time is ?</button>

Change the content of the current element itself

<button onclick = ‘this.innerHTML = Date( )'> Now the time is ?</button>

Event properties call functions directly

<button onclick = 'displayDate()'> Now the time is ?</button>

stay Js The file declares a displayDate( ) function ,html Call... Directly in the document

14. JavaScript character string

JavaScript character string be used for Store and manipulate text

You can use + Wrap a string

for example :document.getElementById("demo").innerHTML ="Hello"+

“Kitty”!;

The string can be passed through key word new Defined as objects ; But it slows down execution

for example :var x = new String("Bill"); Create a Bill object

String addition It's called cascading ( concatenation)

The original properties and methods in the string

  1. length Property returns the length of the string

    var txt = "ABCDEFGHIJKMNA"
    var sln = txt.length;
    
  2. indexOf( ) / lastIndexOf( ) Method Returns the first time of the specified text in the string / The last time The index that appears

    var txt = "ABCDEFGHIJKMNA"
    var pos = txt.indexOf("A");
    // JavaScript from 0 Start index , If no corresponding text is found ,indexOf()/lastIndexOf() All return to -1
    
  3. search( ) Method to search for a string of specific values , And return the matching index

    var txt = "ABCDEFGHIJKMNA"
    var pos = txt.search("A");
    

Be careful indexOf( ) and search( ) The difference between

  • search( ) Method cannot set parameters for the second start position
  • indexOf( ) Method cannot set a more powerful search value ( Regular expressions )
  1. slice( ) / substr( ) Extract a part of the string and return the extracted part in the new string

    slice( param1,param2)

    param1 Indicates the starting index ,param2 Indicates end index

    var txt = "ABCDEFGHIJKMNA"
    var pos = txt.slice(7,14);
    // If a parameter is negative , Then count from the end of the string ( From right to left )
    // If you omit the second parameter , The method will crop the rest of the string
    
  2. replace( ) Method replaces the value specified in the string with another value

    By default ,replace( ) Replace only the first match And sensitive to case

    var txt = "ABCDEFGHIJKMNA"
    var pos = txt.replace(/A/g,"a");
    // Replace all matches , Using regular expressions g Modifier ( Global search ) And regular expressions are not quoted
    
  3. toUpperCase( ) / toLowerCase( ) Convert the string to Big / A lowercase letter

    var txt = "ABCDEFGHIJKMNA"
    var pos = txt.toUpperCase();
    
  4. concat( ) Method to connect two or more strings

    var txt1 = "ABCD"
    var txt2 = "abcd"
    var txt3 = "EFGH"
    var txt = txt1.concat("",txt2).concat("",txt3);
    // concat() Method can be used instead of the addition operator ,txt and txt4 It's equivalent
    var txt4 = "ABCD" + "" + "abcd" + "EFGH";
    
  5. charAt( ) / charCodeAt( ) Return the string to specify the subscript respectively ( Indexes ) String and The character that specifies the index Unicode code

    var txt = "ABCDEFGHIJKMNA"
    var pos = txt.charAt(0);
    // If no character is found , Return to empty string
    
  6. split( ) Convert string to array

    var txt = "a,b,c,d,e"
    var arr = txt.split(",")/txt.split("")/txt.split("|");
    // Use them separately comma 、 Space 、 A vertical bar Separators separate arrays
    // If you omit the separator , The return array contains the entire string
    

15. JavaScript Numbers

JavaScript Unlike other programming languages There is only one numerical type And write numerical value with or without decimal point

JavaScript The value is always based on 64 Bit double precision floating point number to store , According to international IEEE 754 standard

Integer precision ( No scientific counting ) It will be accurate to 15 position

The decimal precision is 17 position , But floating point arithmetic is not always 100% accurate

for example :var x = 0.2 + 0.1 The result will be 0.30000000000000004

Using multiplication and division can help solve the above problems :var x = (0.2 * 10 + 0.1 * 10) // x = 0.3

Numeric string

In all number operations ,JavaScript Will try to convert a string to a number for operation

var x = "100"; var y = 10 ; var z = x / y; // z = 10

It should be noted that , Add the numbers and String concatenation Use both + The sign means , So the above only applies to */- Three operations

var x = "100" ; var y = 10 ; var z = x + y // z = 10010 Instead of 110

NaN ( Non numerical ) The data type is number

NaN (Not a Number ) Belong to JavaScript Reserved words , Indicates a number It's not a legal number

var x = 100 / "a" // x = NaN

For determining whether a value is numeric , We can use the global JavaScript function isNaN( ) To determine , Returns a Boolean value

var x = 100 / "a" ; isNaN(x); // return true

About NaN Some interesting examples of :

var x = NaN; var y = 6; var z = x + y; // z = NaN Instead of 6

var x = NaN; var y ="6"; var z = x + y; // z = NaN5 Instead of NaN Here is the cascade

Infinity ( infinite ) The data type is number

Infinity/-Infinity yes JavaScript The value returned when the maximum possible number range is exceeded when calculating the number

Divide 0 And back again Infinity

var num1 = 2; while (num1 != Infinity) { num1 = num1 * num 1;} // Execute until Infinity

Hexadecimal / octal

JavaScript The prefix will be 0x The numerical constant of is interpreted as Hexadecimal

JavaScript The prefix will be 0 The numerical constant of is interpreted as octal

var x = 0xff; //x = 255

var x = 077; // x = 63 Instead of 77

Use toString( ) Method can be implemented Binary system / octal / Hexadecimal progressive conversion ( Returns... As a string )

var x = 128; var y = x.toString(16); //y = 80

Number Medium Methods and properties

All number methods can be used for any type of number ( Literal ( Constant )、 Variable 、 expression )

  1. toString( ) Method Returns a numeric value as a string

    var x = 123;
    x.toString(); // Dependent variable x return 123
    (123).toString(); // From constant return 123
    (100 + 24).toString(); // From expression return 124
    
  2. toExponential( param ) / toFixed(param ) Method To return string values , Inclusion has been rounded and counted exponentially / Returns the specified number of decimal places directly The number of

    param Defines the number of characters after the decimal point , Parameters can be chosen , If not set ,JavaScript No rounding of numbers

    var x = 98.8998;
    x.toExponential(3); // return 9.890e+1
    x.toExponential(); // return 9.88998e+1
    x.toFixed(2); // return 98.90 It's good for dealing with numbers about money
    
  3. toPrecision(param ) Returns a numeric value as a string , Contains the specified length

    var x = 98.8998
    x.toPrecision(3) // return 98.9
    
  4. valueOf( ) Returns a number as a number

    stay JavaScript in , The number can be Original value (typeof = number ) or object (typeof = object )

    stay JavaScript Inside Use valueOf( ) The method can be Number object Convert to Original value

    all JavaScript data type There are valueOf( ) and toString( ) Method

    var x = 123;
    x.valueOf(); // Dependent variable x return 123
    (123).valueOf(); // Literally 123 return 123
    (100+25).valueOf(); // From expression 100+25 return 125
    
  5. On the global method of numerical value

    JavaScript The global method Can be used for all JavaScript data type

  • Nubmer( ) Method hold JavaScript Variable Convert to numeric , From the transformation of its parameters

    x = true ; Number(x); // return 1
    x = new Date(); Number(x); // return 1611294882633 In the form of timestamps
    x = "10 20" ; Number(x); // return NaN
    
  • parseInt( ) / parseFloat( ) Method to parse a string , Allow Spaces , Respectively by Integers / Returns the first number as a floating-point number

    parseInt ("10.33"); // return 10
    parseFloat ("10.33"); // return 10.33
    

    Digital properties

    The number attribute belongs to a class named number Of JavaScript Digital object wrapper , Only on number This digital object works

  1. MAX_VALUE / MIN_VALUE Property returns JavaScript The largest possible / Minimum Numbers

    var x = Number.MAX_VALUE; // return 1.7976931348623157e+308
    var x = Number.MIN_VALUE; // return 5e-324
    
  2. POSITIVE_INFINITY / NEGATIVE_INFINITY Attribute representation just / negative The infinity of , Return this property when overflowing

    var x = Number.POSITIVE_INFINITY; // return infinity
    var x = Number.NEGATIVE_INFINITY; // return -infinity
    
  3. NaN attribute It means not a number

    var x = Number.NaN;
    

16. JavaScript Array

Arrays are special variables , It can store more than one value at a time ; And you can access these values by referring to the index number

Grammatical structure

var arrayName = [item1 , item2 , …] ;

Access arrays and their elements

An array is an object , It can be used directly by reference Array name to access the complete array

By quoting index numbers ( It's labeled ) To access an array element

var varName = arrayName[ n] ;

Array elements can also be objects

JavaScript Variables can be objects ; Arrays are special types of objects

Because of this , You can store different types of variables in the same array

Arrays can hold objects , Arrays can also hold functions , Even arrays can be saved in arrays

The original properties and methods of an array

  1. length attribute Returns the length of the array ( The number of array elements )

    var person = [Jim,Tom,Sam,Tim]
    var personNumber = person.length; // personNumber = 4
    
  2. Visit the first / the last one Array elements

    var person = [Jim,Tom,Sam,Tim]
    var firstPerson = person[0]; // return firstPerson = Jim
    var lastPerson = person[person.length - 1]; // return lastPerson = Tim
    
  3. Traversing array elements

    for loop / Array.foreach( ) Can be used to traverse arrays

    var person , personNumber , personText , i;
    person = [Jim,Tom,Sam,Tim];
    personNumber = person.length;
    personText = "<ol>"
    for (i = 0 ; i < personNumber;i++ ) {
    personText += "<li>" + person[i] + "</li>";
    }
    text += "</ol>"
    var person , personText;
    person = [Jim,Tom,Sam,Tim];
    personText = "<ul>";
    person.forEach(myFunction);
    personText += "</ul>";
    document.getElementById("demo").innerHTML = personText;
    function myFunction(value){
    personText += "<li>" + value + "</li>";
    }
    
  4. push( ) Method and length attribute You can add new elements to the array ;pop( ) Method Remove the last element from the array

    var person = [Jim,Tom,Sam,Tim];
    person.push("Dom"); // Add an element from the end of the array "Dom"
    person.push(); // return Length of new array 5
    person[person.length] = "Xom";
    person.pop(); // Delete the last element “Xom”; Returns the ejected value "Xom"
    
  5. Associative array

    Many programming elements support arrays of named indexes

    An array with a named index is called Association element group ( Or hash )

    JavaScript I won't support it Array of named indexes

    stay JavaScript in , Arrays can only use Digital index

    var person = [];
    person[0] = "Jim";
    person[1] = "Tom";
    person[2] = "Sam";
    var x = person.length; // x = 3;
    var y = person[0]; // y = "Jim";
    // If in JavaScript Using named indexes in ,JavaScript Will redefine arrays as standard objects
    // after , All array methods and properties will produce incorrect results
    var person = [];
    person["fistName"] = "Jim";
    person["secondName"] = "Tom";
    person["lastName"] = "Sam";
    var x = person.length; // x = 0 ;
    var y = person[0]; // y = undefined;( Undefined )
    
  • The difference between arrays and objects

    JavaScript in , Using an array Digital index ; Object use Name the index

    namely The element name is string ( Text ) We should use objects ; The element named number should be an array

  1. How to identify whether a variable is an array
  • ECMAScript 5 New methods are defined Array.isArray( ) , Return Boolean value to judge

    Array.isArray(person);
    
  • establish isArray( ) function , Return Boolean value to judge

    function isArray(person){
    return person.constructor.toString().indexOf("Array")> -1 ;
    }
    // If the object prototype contains words "Array", Then return to true
    
  • If the object is created by a given constructor , be instanceof Operator return true

    var person = [Jim,Tom,Sam,Tim];
    person instanceof Array
    
  1. toString( ) / join( ) Method Convert an array to a string of array values

    var person = [Jim,Tom,Sam,Tim];
    person.toString(); // return Jim,Tom,Sam,Tim By default, comma separated
    person.join("*"); // return Jim * Tom * Sam * Tim Separators can be specified
    

17. JavaScript Array synthesis

Displacement elements

Displacement is the same as pop-up , But deal with the first element instead of the last

  1. shift ( ) Method will delete the first array element , And put all the other elements “ Displacement ” To a lower index

    var person = [Jim,Tom,Sam,Tim];
    person.shift(); // Delete the first element “Jim”, Can return the deleted element “Jim”
    
  2. unshift( ) Method ( At the beginning ) Add a new element to the array , and “ Reverse displacement ” Old elements

    var person = [Jim,Tom,Sam,Tim];
    person.unshift("Dom"); // stay person Add a new element at the beginning of the array “Dom”
    person.unshift(); // Returns the length of the new array 5
    

Splicing and deleting elements

  1. delete Operator You can delete the value of the element in the array with the specified index , And the array structure doesn't change

    var person = [Jim,Tom,Sam,Tim];
    delete person[1]; // hold person The second element in the array “Tom” Delete
    // Use delete Will leave undefined... In the array (undefined) The emptiness of ; Please use pop() or shift() Instead,
    
  2. splice(param1 ,param2, param3 … ) Method can be used to add a new item to an array

    param1 Define the index location where the new element should be added ( Splicing )

    param2 Defines how many elements should be removed

    The rest of the parameters Define the new element values that need to be added

    var person = [Jim,Tom,Sam,Tim];
    person.splice(1,1,"Dom","Xom"); // Delete "Tom", And add after that “Dom” and "Xom"
    

    adopt splice( ) Method Deletes the specified element , To avoid undefined holes

    var person = [Jim,Tom,Sam,Tim];
    document.getElementById("demo1").innerHTML =" The second person is :"+ person[1];
    person.splice(1,1);
    document.getElementById("demo2").innerHTML =" The second person is :"+ person[1];
    // Elements id ="demo1" return "Tom"
    // Elements id =”demo2“ return "Sam"
    // It can be found that ”Tom“, The original array structure, that is, the number index, has changed
    

Merge ( Connect ) Array

  1. concat( ) Methods by merging ( Connect ) Existing array to create a new array

Changing the method does not change the existing array , And always returns a new array ; And you can use any number of array parameters ( Merge multiple arrays )

var arr1 = ["1","2","3"];
var arr2 = ["4","5"];
var arr3 = ["6","7","8"];
var arr4 = ["9","10"];
var arr0 = arr1.concat(arr2,arr3,arr4); // Connect 4 An array
var arr5 = arr1.concat("6","7");
// concat Parameters can also be specific element values

Crop array

  1. slice( param1 , param2 ) Method Use a fragment of the array to cut out a new array

    The method is to create a new array , Without removing any elements from the source array

    param1 Defines the start index position of the interception ;param2 Defines the end index position of the interception ( Not including closing index )

    var person = [Jim,Tom,Sam,Tim];
    var american = person.slice(1,3); // Return a new array [Tom,Sam]
    var nords = person.slice(1); // Return a new array [Tom,Sam,Tim]
    

Array sorting

  1. sort ( ) Method Sort arrays in alphabetical order

    var person = [Jim,Tom,Sam,Dom];
    person.sort(); // return [Dom,Jim,Sam,Tom]
    
  2. adopt sort( ) Do... On a number array Ascending / Descending

    // Ascending
    var points = [2,5,68,83,3,6,14,48];
    points.sort(
    function (a,b) {
    return a - b;
    }
    );
    // Descending
    var points = [2,5,68,83,3,6,14,48];
    points.sort(
    function (a,b) {
    return b - a;
    }
    );
    // Here's the ratio function , When sort() When the function compares two values , The value is sent to the comparison function
    // And based on the returned value ( negative / zero / Comes at a time ), Sort two numbers
    // such as 48 and 14 ; 48-14=34>0 The sort function will put 38 The order is ratio 14 Higher values
    // a-b>0 That is, the return value is positive , be a row b Back ; a-b<0 That is, the return value is negative be a row b front
    
  3. reverse( ) Method Reverse sort the array ( Descending )

    var person = [Jim,Tom,Sam,Dom];
    person.reverse(); // return [Tom,Sam,Jim,Dom]
    

Find the most value in the array

  1. JavaScript No built-in function to find the maximum or minimum value in an array

    But after sorting , The highest or lowest value can be obtained according to the array index ; Of course, this efficiency is extremely low

    var points = [2,5,68,83,3,6,14,48];
    points.sort(
    function (a,b){
    return a - b;
    }
    );
    var pointsMin = points[0]; // Returns the minimum value of the array 2
    var pointsMax = points[points.length-1]; // Returns the maximum value of the array 83
    
  2. Math.max.apply / Math.min.apply You can find out the largest... In the array / Minimum value

    Math.max.apply( [ 1 , 2 , 3 ] ) Equivalent to Math.max( 1 , 2 , 3 )

     function myArrayMax(points) {
    return Math.max.apply(null ,points);
    }
    // Return maximum 83
    
  3. Achieve your own goals

    By traversing the array , Compare each value with the highest value found

    var points = [2,5,68,83,3,6,14,48];
    function myArrayMax(points) {
    var pointsLength = points.length;
    var pointsMax = - Infinity;
    while (pointsLength --) {
    if (points[pointsLength] > pointsMax ) {
    pointsMax = points[pointsLength];
    }
    }
    return pointsMax;
    }
    // return pointsMax = 83;
    

Object array sorting

  1. JavaScript Array It often contains objects

    Even if an object has properties of different data types ,sort( ) Method can sort arrays by comparing their property values

    // Compare numeric attributes
    var car = [{type:"Volvo",year:2016},{type:"Cadillac",year:2018},{type:"BWM",year:2017}];
    car.sort(
    function (a,b) {
    return a.year - b.year;
    }
    );
    // Compare string properties
    var car = [{type:"Volvo",year:2016},{type:"Cadillac",year:2018},{type:"BWM",year:2017}];
    car.sort(
    function (a,b) {
    var x = a.type.toLowerCase();
    var y = b.type.toLowerCase();
    if (x < y) {
    return -1;
    }
    if (x > y) {
    return 1;
    }
    }
    );
    

Array iteration

  1. forEach( ) Method Call the function once for each array element ( Callback function )
var txt = "";
var points = [2,5,68,83,3,6,14,48];
points.forEach(myFunction);
function myFunction(value,index,array) {
txt = txt + value + "<br>";
}
// The function called can receive 3 Parameters Namely Item value :value ; Project index :index; The array itself :array
// myFunction This function is passed as an argument , It's a feature of callback functions
  1. map( ) Method performs a function on each array element to create a new array

This method does not perform functions on array elements that have no values ; And does not change the source array

var points = [2,5,68,83,3,6,14,48];
var newPoints = points.map();
function myFunction(value,index,array ) {
return value * 2;
}
// Return a new array newPoints = [4,10,136,166,6,12,28,96]
  1. filter( ) Method to create a new array containing elements that are filtered by some condition
var points = [2,5,68,83,3,6,14,48];
var over20 = points.filter(myFunction);
function myFunction(value,index,array) {
return value > 20;
}
// Return a new array over20 = [68,83,48]
  1. reduce( ) / reduceRight( ) Method runs the function on each array element , To generate ( Reduce it ) Single value

This method works from left to right in the array by default , The difference in reduceRight( ) ; Without reducing the source array

reduceRight( ) Working from right to left , From the end of the array to the beginning of the array

var points = [2,5,68,83,3,6,14,48];
var sum = points.reduce(myFunction);
function myFunction(total,value,index,array) {
return total+value;
}
// return sum = 229
// The function called can receive 4 Parameters
// Namely total ( Initial value / Previously returned values ):total; Item value :value; Project index :index; The array itself :array
// reduce() Method can receive an initial value
var points = [2,5,68,83,3,6,14,48];
var sum1 = points.reduce(myFunction,100);
function myFunction(total,value,index,array) {
return total+value;
}
// return sum1 = 329
  1. every( ) Method to check whether all the elements in the array pass the filtering of a certain condition , Returns a Boolean value

This method is different from some( )

some( ) The method is to detect whether the values of some array elements in the array are filtered , As long as there is a 1 individual , Then return to true

var points = [2,5,68,83,3,6,14,48];
var allOver20 = points.every(myFunction);
function myFunction(value,index,array) {
return value > 20;
}
// return allOver20 = false
  1. indexOf( item ,start ) / lastIndexOf( item,start) Method searches the array for element values and returns the position , From the beginning to the end / From the end to the beginning

item Define the items that need to be retrieved ; start Define where to start the search

var points = [2,5,68,83,3,6,14,48];
var a = points.indexOf(3); // return a = 4
var b = points.lastIndexOf(3); // return b = 3
// If the specified value is not retrieved , return -1
  1. findIndex( ) Method returns the index of the first element of an array filtered by a condition

    var points = [2,5,68,83,3,6,14,48];
    var first = points.findIndex(myFunction);
    function myFunction(value,index, array) {
    return value > 18;
    }
    // return first = 2
    

18. JavaScript date

UTC ( Coordinated Universal Time) World coordinated time 、 Universal time 、 World standard time

It's the most important time in the world , The reason is that Atomic time Seconds are the basis , Try to be as close to as possible in time GMT

GMT (Greenwish Mean Time) Greenwich mean time 、 Greenwich mean time

It refers to the local flat solar time of the Royal Greenwich Observatory in the suburb of London

Because the prime meridian was defined as the meridian passing through there

Beijing is the time be equal to UTC+8 be equal to GMT+8

By default , JavaScript The time zone of the browser is used and the date is displayed as a full-text string

Sat Jan 23 2021 00:15:13 GMT+0800 (GMT+08:00)

Be careful :JavaScript from 0 To 11 Calculate the month

  1. new Date( ) Create a new... With the current date and time static state Date object

    Date( ) The object has a new Date( ) Constructor creation

    var now = new Date();

  2. new Date( year , month , day ,hours, minutes ,seconds,milliseconds) Create a new date object with the specified date and time

    7 The numbers stand for year / month / Japan / Hours / branch / second / millisecond , Order cannot be changed

var now = new Date(2021,1,22,00,21); // return Mon Feb 22 2021 00:21:00 GMT+0800 (GMT+08:00)

  1. new Date (dateString) Create a new date object from the date string

    var now = new Date("Janury 22 ,2021 ,00:23:47") // return Fri Jan 22 2021 00:23:47 GMT+0800 (GMT+08:00)

  2. new Date(milliseconds) Create a new date object in the form of a timestamp

    Note that the conversion format is millisecond (milliseconds) convert

    var now = new Date(1611333032000); // return Sat Jan 23 2021 00:30:32 GMT+0800 (GMT+08:00)

Date format

Full format :( YYYY-MM-DDTHH:MM:SS )

Short date format :(MM/DD/YYYY) for example :( “02/19/2018” )

Long date format :(MMM DD YYYY) for example :(“Feb 23 2021”)

Date and time in capital letters T To separate

UTC Time is written in capital letters Z To define

The time zone

Set up / obtain Date time , If you don't specify a time zone ,JavaScript The time zone of the browser is used by default

let me put it another way , If the date / Time to GMT establish , This date / Time will be converted into CST ( China standard time ), When users use browsers in China

Set up / How to get the date

Set up (set) / obtain (get)

It should be noted that :JavaScript month 、 Zhou 、 Hours 、 minute 、 second 、 millisecond All from 0 Start counting , And the sky is from 1 Start counting

for example :getDate( ) Method Returns days as a number (1-31)

​ getMinutes( ) Method Get the number of points (0-59)

Setting date :https://www.w3school.com.cn/js/js_date_methods_set.asp

Get date :https://www.w3school.com.cn/js/js_date_methods.asp

19. JavaScript Mathematical synthesis

JavaScript Math

JavaScript Math Object can perform mathematical tasks on numbers

  1. 8 It's a mathematical constant

    JavaScript It can be provided by Math Object access 8 It's a mathematical constant

    attribute meaning
    Math.E Back to the Euler index (e) e = 2.718281828459045
    Math.PI Return the PI π = 3.141592653589793
    Math.SQRT2 return 2 The square root of \(\sqrt{2}\) = 1.4142135623730951
    Math.SQTR1_2 return ½ The square root of \(\sqrt{½}\) = 0.7071067811865476
    Math.LN2 return 2 The natural logarithm of \(\log_e 2\) = 0.6931471805599453
    Math.LN10 return 10 The natural logarithm of \(\log_e 10\) = 2.302585092994046
    Math.LOG2E 2 The natural logarithm of the base \(\log_2 e\) = 1.4426950408889634
    Math.Log10E 10 The natural logarithm of the base \(\lg e\) = 0.4342944819032518
  2. Math.round(x) Method return value is x The nearest integer to be rounded

    Math.round(8.8); // return 9

  3. Math.pow(x,y) Method return value is x Of y The next power

    Math.pow(3,3); // return 9

  4. Math.sqrt(x) Method returns x The square root of

    Math.sqrt(16); // return 4

  5. Math.abs( x) Method returns x Absolute ( just ) value

    Math.abs(-3.8) // return 3.8

  6. Math.ceil(x) / Math.floor(x) Method returns a value x Up / Down Round to the nearest integer

    Math.ceil(6.3); // return 7

    Math.floor(6.3); // return 6

  7. Math.sin(x) / Math.cos(x) / Math.tan(x) / Math.asin(x) / Math.acos(x) / Math.atan(x)

    Method return x ( In radians ) Of just / cosine ( Be situated between -1 To 1 Between the value of the ) / tangent / Anyway / cosine / tangent

    angle = radian * Math.PI /180

    Math.sin( 90 * Math.PI/180) // namely sin (π/2) = 1

  8. Math.random( ) Method returns Greater than or equal to 0 And less than 1 Random number between (16 Decimal place )

    Math.random(); // return 0.7163944549620018

    Math.random( ) and Math.floor( ) Used together to return random integers

    Math.floor(Math.random() * 10); // return 0~9 Integer between
    Math.floor(Math.random() * 100); // return 0~99 Integer between
    Math.floor(Math.random() * 10) + 1 ; // return 1~10 Integer between
    Math.floor(Math.random() * 11); // return 0~10 Integer between
    

    A proper random function

    document.getElementById("demo").innerHTML = getRndInteger(1,10);
    function getRndInteger(min,max) {
    return Math.floor(
    Math.random() * ( max - min)
    ) + min;
    }
    // return 1 >= And <= 9 Random integer between namely (min <= x< max)
    document.getElementById("demo").innerHTML = getRndInteger(1,10);
    function getRndInteger(min,max) {
    return Math.floor(
    Math.random() * ( max - min + 1)
    ) + min;
    }
    // return 1~10( All include ) Random integer of namely ( min =< x <= max)
    
  9. atan2(y,x) Method to return from x Axis To spot (x,y) The angle of

    Math.atan2(0,1); // return 0

  10. log(x) Method returns x The natural logarithm of (e Bottom )

    Math.log(1); // return 0

JavaScript Boolean( Logic )

Usually , In programming , There are many data types for one of the two values

Such as YES/NO ; ON/OFF ; TRUE/FALSE

In view of this ,JavaScript Provides a Boolean data type , It only receives value true or false

  1. Boolean( ) Method Determine the expression ( Or variable ) Is it true

    Boolean(10 > 8); // return true
    Boolean(0); // return false
    Boolean(-0); // return false
    Boolean(""); // return false
    Boolean(x); // stay x Returns if the statement is not assigned false
    Boolean(null); // return false
    Boolean(false); // return false
    Boolean(NaN); // return false
    

20. JavaScript condition loop

Conditional statements are used to perform different actions based on different conditions

if sentence

  1. grammar

    if( Conditions ) {
    If the condition is true when Executed code
    }
    
    if (hour < 18) {
    greeting = "Good day";
    }
    // If the time is earlier than 18:00, Send out "Good day" Greetings from
    

if…else sentence

  1. grammar

    if( Conditions ) {
    Condition is true The code block to execute when the
    } else {
    Condition is false The code block to execute when the
    }
    
    if (hour< 18) {
    greeting = "Good day";
    } else {
    greeting = "Good evening";
    }
    // If the time is earlier than 18:00, issue "Good day" Greetings from , otherwise issue "Good evening"
    

else…if sentence

  1. grammar

    if( Conditions 1) {
    Conditions 1 by true The code block to execute when the
    } else if( Conditions 2) {
    Conditions 1 by false And the conditions 2 by true The code block to execute when the
    } else {
    Conditions 1 and Conditions 2 Also for false The code block to execute when the
    }
    
    if (hour < 10) {
    greeting = "Good morning";
    } else if (hour < 18) {
    greeting = "Good day";
    } else {
    greeting = "Good evening";
    }
    // If the time is earlier than 10:00 , issue "Good moring" Greetings from , If not , And earlier than 18:00, issue "Good day" Greetings from
    // If none of the above is , Send out "Good evening" Greetings from
    

switch sentence

switch Statement is used to select one of several code blocks to be executed

  1. grammar

    switch( expression ) {
    case n:
    Code block
    break;
    case n:
    Code block
    break;
    default:
    Default code block
    }
    // Calculate once switch expression ; Combine the value of the expression with each case Compare the values of ; If the match , Then execute the associated code
    // break key word Interrupt jump out switch Code block
    // default key word The rules don't exist case Code that runs by default when matching ; It's not the last one , It can be placed anywhere
    
    var day;
    switch (new Date().getDay()) {
    case 0 :
    day = " Sunday ";
    break;
    case 1 :
    day = " Monday ";
    break;
    case 2 :
    day = " Tuesday ";
    break;
    case 3 :
    day = " Wednesday ";
    break;
    case 4 :
    day = " Thursday ";
    break;
    case 5 :
    day = " Friday ";
    break;
    case 6 :
    day = " Saturday ";
    // There's no need to interrupt switch The last one in the code block case; The code block naturally ends here
    }
    
    // Different case Use the same code
    var text;
    switch(new Date().getDay()) {
    case 4:
    case 5:
    text = " The weekend is coming :)";
    break;
    case 0:
    case 6:
    text = " Today is the weekend ~";
    break;
    default:
    text = " Looking forward to the weekend !";
    }
    

If there are many case Match one case value , Choose the first one case

If no match is found case And no code block was found for default execution , The program will continue switch The following sentence

switch case The value of must be the same as the type to match ( Strict comparison ===)

The ternary operation

Ternary operations are suitable for assigning values to variables based on certain conditions

  1. grammar

    varName = ( Conditions )? value1 : value2
    // If the condition is true be varName Assigned value1; Otherwise it is assigned value2
    
    var voteable = (age < 18) ? "To young" "Mature enough"
    

loop Apply to You need to run some code many times , And different values are used each time

for loop

for loop Traversing code blocks multiple times

  1. grammar

     for( sentence 1 ; sentence 2 ; sentence 3) {
    Block of code to execute
    }
    // sentence 1 Execute before the loop starts ( initialize value , It can be more than one , use "," commas )
    // sentence 2 Define the conditions for running the cycle ( Under what conditions is the loop executed )
    // sentence 3 Will be executed every time the loop is executed ( Usually incrementing / Minus the value of the initial variable )
    // sentence 1 and sentence 3 Can be declared in other places , however ";" The separator can't be less
    
    var cars = ["BMW","Volvo","Porsche","Ford"];
    var i,len,text;
    for(i = 0 ,len = car.length ,text = "";i < len ;i ++) {
    text += car[i] + "<br>";
    }
    

for / in loop

for / in loop Traversing the properties of an object

  1. Example

    var person = { fanme:"Bill",lname:"Gates",age:62};
    var text = "";
    var x ;
    for (x in person) {
    text += person[x];
    }
    

while loop

while The loop loops the code block all the time , As long as the specified condition is true

  1. grammar

     while( Conditions ) {
    Block of code to execute
    }
    
    var i,text;
    while (i < 10) {
    text += " The number is " + i;
    i ++ ;
    }
    // as long as Variable i<10, The code block will always execute ; Remember to increment the variable / Reduction of operating
    

do / while loop

do / while loop yes while A variant of the cycle

Before checking if the condition is true , This loop executes the code block once , And then as long as the condition is true, the loop repeats

  1. grammar

    do {
    Block of code to execute
    }
    while ( Conditions )
    
    var i = 0.1;
    var text = "";
    do {
    text += "<br> The number is " + i;
    i++;
    }
    while (i < 10)
    

for loop And while loop The difference between

  1. Example

    var cars = ["BWM","Volvo","Saab","Ford"];
    var i = 0;
    var text = "";
    for(;cars[i];) { // The separator number cannot be less
    text += cars[i] + "<br>";
    i ++;
    }
    var cars = ["BWM","Volvo","Saab","Ford"];
    var i = 0;
    var text = "";
    while(cars[i]) {
    text += cars[i] + "<br>";
    i ++;
    }
    

break and continue

break sentence It's not just for jumping out switch Code block , It can also be used to jump out of a loop

continue sentence “ skip ” An iteration in the loop

Notice the difference between the two

  1. Example

    var text = "";
    var i = 0;
    for (i = 0;i < 10;i ++) {
    if(i===3){ break;}
    text += " The number is " + i + "<br>";
    }
    // This loop can only traverse i = 0 , 1 ,2 These three situations
    // When i = 3 when , Have gone through break Statement out of loop , Execute the following code
    
    var text = "";
    var i = 0;
    for (i = 0;i < 10;i ++) {
    if(i===3){ continue;}
    text += " The number is " + i + "<br>";
    }
    // This loop can traverse except i = 3 This situation , Everything else goes through
    // When i = 3 when , Have gone through continue Statement jumps out of the iteration of the current loop , Execute the next iteration in the cycle
    

21. JavaScript abnormal

When executed JavaScript Code , All kinds of mistakes can happen

The error could be a coding error 、 Errors or other unforeseen problems caused by input formats

JavaScript Has a built-in... That provides error information when an error occurs error object

error Object provides two useful properties : name and message

  1. name attribute : Set or return error name

    name Property returns the value describe
    EvalError Already in eval( ) Error in function
    RangeError An error has occurred that is out of the range of numbers
    ReferenceError An extraordinary reference has occurred
    SyntaxError A syntax error has occurred
    TypeError A type error has occurred
    URIError stay encodeURI( ) What happened in
  2. message attribute : Set or return error messages ( A string )

Like any other programming language , When the program runs abnormally , An exception will be thrown ( error ) For programmers , To handle exceptions or errors

try and catch sentence

JavaScript sentence try and catch Pairs appear

try sentence Allows you to define a code block , To detect errors when executing

catch sentence Allows you to define a block of code to execute , If try Error in code block ( How to deal with errors )

  1. grammar

     try {
    Code block for testing
    }
    catch(err) {
    Code blocks that handle errors
    }
    
    <p id = "demo"> </p>
    <script>
    try {
    adddlert(" Welcome to visit !");
    }
    catch(err) {
    document.getElementById("demo").innerHTML = err.message;
    }
    </script>
    // return adddlert is undefinded
    

throw sentence

throw sentence Used to throw a user-defined exception

If you put throw And try and catch Use together , You can control the program flow and generate custom error messages

  1. Example

    function getRectArea(width,heigth) {
    if (isNaN(width) || isNaN(heigth)) {
    throw `Parameter is not a number!`;
    }
    }
    try {
    getRectArea(3,'A')
    }
    catch (err) {
    console.error(err);
    }
    // return `Parameter is not a number!`
    

finally sentence

finally sentence stay try and catch Then execute the custom code , Whatever the outcome

  1. grammar

     try {
    Code block for testing
    }
    catch(err) {
    Code blocks that handle errors
    }
    finally {
    No matter what try and catch The result is how to execute the code block
    }
    
    function myFunction() {
    var message, x;
    message = document.getElementById("message");
    message.innerHTML = "";
    x = document.getElementById("demo").value;
    try {
    if(x == "") throw " It's empty. ";
    if(isNaN(x)) throw " Not numbers ";
    x = Number(x);
    if(x > 10) throw " Too big ";
    if(x < 5) throw " Too small ";
    }
    catch(err) {
    message.innerHTML = " error :" + err + ".";
    }
    finally {
    document.getElementById("demo").value = "";
    }
    }
    

22. JavaScript Scope

A scope is a collection of variables that you have access to

Scope determines Look at variables from different parts of the code 、 object And the accessibility of functions

JavaScript Scoped 3 Kind of type

  • Global scope ( Global scope )
  • Local scope ( Local scope)
  • Block scope ( Block scope)

JavaScript Have Function scope , That is, each function creates a new scope , Scope determines the accessibility of these variables ( visibility )

Variables defined inside a function are not accessible from outside the function ( Invisible )

Local / overall situation Variable

stay JavaScript Within the function Declared variables , It becomes a local variable of the function ; The scope of a local variable is local , That is, they can only be accessed inside functions

Function parameters are also local variables in a function

Local variables are created at the beginning of the function , They are deleted at the end of the function

Variables declared outside of functions , It becomes a global variable ; The scope of a global variable is global , namely All scripts and functions of the web page can access it

Unless it is done intentionally , Otherwise, do not create global variables , Global variables are easy to override

JavaScript Hoisting

hoisting ( promote ) yes JavaScript take All declarations are promoted to the default behavior at the top of the current scope ( To the top of the current script or function )

hoisting Do not apply to JavaScript Strict mode

JavaScript Only promote Variable declarations , Do not promote variable initialization

  1. Example

    var x = 5;
    var y = 7; // initialization x / y
    elem = document.getElementById("demo"); // Look for the element
    elem.innerHTML = x + "" + y; // Display element x and y
    return 5 7
    var x = 5 ;
    elem = document.getElementById("demo");
    elem.innerHTML = x + "" + y ;
    var y = 7 ;
    return x undefinded
    // y It is only declared that , But not assigned , So it is undefinded
    

JavaScript Strict Pattern

Strict mode Defined JavaScript The code should be in “ Strict mode ” standard perform ; To be compatible with earlier versions of JavaScript

adopt stay The beginning of a script or function add to “use strict” ; To declare strict patterns And can only be recognized at the beginning of a script or function

In strict mode , like Wrong variable name 、 In the case of assigning a value to a non writable property , Will throw an exception or error ; The normal model doesn't

Be careful :

  1. stay strict In the pattern , In the absence of a statement Variable ( Object etc. ) On the premise of Assign values to variables directly It's not allowed
  2. Delete variables ( object 、 Functions, etc ) It's not allowed
  3. Octal numeric text 、 Escape character It's not allowed
  4. write in read-only 、 You can only get attribute It's not allowed
  5. “eval” 、 “arguments” A string cannot be used as a variable ; And eavl( ) Functions cannot pass arguments when called
  6. with sentence It's not allowed

let and const

let and const Two keywords stay JavaScript in Statement provided Block scoped variables and constants

adopt var key word Declared variables No, Block scope ; namely In block { } Inside Declared variables can be retrieved from block outside Visit

  1. Example

     var x = 10 ;
    {
    var x = 6 ;
    }
    // Block scope
    // here x by 6
    var i = 7 ;
    for ( var i = 0 ; i < 10 ; i ++) {
    // Some sentences
    }
    // Loop scope ,i Can be accessed outside the loop , It's out of the loop
    // here i by 10
    

and let Solved this problem

  1. Example

    let i = 7 ;
    for (let i = 0 ; i < 10 ; i ++) {
    // Some sentences
    }
    // here i by 7
    

HTML Global variable in

stay HTML in The global scope is window That is, all global variables belong to window object

adopt var Keywords are defined by Global variables Belong to window object

adopt let key word Defined Global variables Do not belong to window object

  1. Example

    var carName = " porsche";
    // The code here is available window.carName
    let carName = "porsche";
    // The code here is not available window.carName
    

var and let / const The other differences between them

  1. Allow anywhere in the program Use var To declare JavaScript Variable

    var x = 10;
    var x = 5;
    // Now? x by 5
    
  2. In the same scope or In the same block , adopt let To declare One (var Variable / let Variable ) / adopt var To declare One let Variable It's not allowed

    var x = 10; // allow
    let x = 6; // Don't allow
    {
    var x = 10; // allow
    let x = 6; // Don't allow
    }
    let x = 5 ; // allow
    var x = 6 ; // Don't allow
    {
    let x = 5; // allow
    var x = 6; // Don't allow
    }
    let x = 5; // allow
    let x = 6; // Don't allow
    {
    let x = 5; // allow
    let x = 6; // Don't allow
    }
    
  3. In different scopes or block in , adopt let Redefining variables is allowed

    let x =6; // allow
    {
    let x = 7 ; // allow
    }
    {
    let x = 8 ; // allow
    }
    
  4. adopt var Declarative Variables will be raised to the top ; and adopt let Declared variables Will not be

// Here, , You can use carName
var carName;
// Here, , You may not use carName
let carName;

23. JavaScript this key word

JavaScript this The key word is What it belongs to

It has different values , Depending on where it's used

  • In the method , this refer to The owner object

  • Alone , this refer to Global object

  • In the function , this The global object

  • In the function , In strict mode this yes undefined

  • In the event category , this The element that receives the event

    // In the method ,this refer to person object ;person The object is fullName The owner of the
    var person = {
    firstName : "Bill",
    lastName : "Gates",
    id : 9527,
    fullName : function () {
    return this.firstName + " " + this.lastName;
    }
    };
    // The default mode , A separate this, this refer to Global object ; In the browser window , The global object is [object Window]
    var x = this;
    // return [object Window]
    // In strict mode , If used alone , that this The global object [ object Window]
    "use strict";
    var x = this;
    // return [object Window]
    function myFunction( ) {
    return this;
    }
    // In default mode ,this It's the function owner I.e. global object [object Window]
    "use strict";
    function myFunction( ) {
    return this;
    }
    // In strict mode ,this Is undefined state undefined
    <button onclick = "this.style.display = 'none' "> Click to delete me !</button>
    

24. JavaScript Reserved words

  1. JavaScript Reserved words

    stay JavaScript in , It should be avoided Will retain words As a variable 、 Mark or Function name to use

    | abstract | double | in | super |
    | :--: | | | |
    | arguments | else | instanceof | switch |
    | await | enum | int | synchronized |
    | boolean | eval | interface | this |
    | break | export | let | throw |
    | byte | extends | long | throws |
    | case | false | native | transient |
    | catch | final | new | true |
    | char | finally | null | try |
    | class | float | package | typeof |
    | const | for | private | var |
    | continue | function | protected | void |
    | debugger | goto | public | volatile |
    | default | if | return | while |
    | delete | implements | short | with |
    | do | import | static | yield |

  2. JavaScript object 、 Properties and methods

stay JavaScript in Use should be avoided JavaScript The name of the built-in object 、 Properties and methods

Array Date eval function
hasOwnproperty Infinity isFinite isNaN
isPrototypeOf length Math NaN
name Number Object prototype
String toString undefined valueOf
  1. Java Reserved words

    JavaScript often And Java Use it together , We should avoid putting some Java object And attributes as JavaScript identifier

    getClass java javaArray
    javaClass javaObject javaPackage
  2. HTML and Window Objects and properties

    JavaScript It can be used as a programming language in many applications , Should be avoided HTML and Window Names of objects and properties

    alert element navigator plugin
    all elements frames prompt
    anchor embed frameRate propertyIsEnum
    anchors embeds hidden radio
    area encodeURI history rest
    assign encodeURIComponent image screenX
    blur escape images screenY
    button event offscreenBuffering scroll
    checkbox fileUpload open secure
    clearInterval focus opener select
    clearTimeout form option self
    clientInformation forms outerHeight setInterval
    close frame outerWidth setTimeout
    closed innerHeight packages submit
    confirm innerWidth pageXOffset taint
    constructor layer pageYOffset text
    crypto layers parent textarea
    decodeURI link parseFloat top
    decodeURIComponent location parseInt unescape
    defaultStatus mimeTypes password untaint
    document nevigate pksc11 window
  3. HTML Time handler

    You should also avoid using all HTML The name of the event handler

    onblur onclick onerror onfocus
    onkeydown onkeypress onkeyup onmouseover
    onload onmouseup onmousedown onsubmit
版权声明
本文为[Venusoooooo]所创,转载请带上原文链接,感谢
https://javamana.com/2021/01/20210124155618153v.html

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云