A basis,

1. Data types

  • Value types (basic types) : String, Number, Boolean, Null, Undefined, Symbol
  • Reference data types: Object, Array, Function

The JavaScript variable life cycle is initialized when it is declared, local variables are destroyed after the function completes execution, and global variables are destroyed after the page closes. Function parameters are local variables that only work within a function.

2. Type conversion

methods role
Number() Convert to numbers
String () and toString () Convert to string
Boolean() Converts to a Boolean value
toFixed() Converts a number to a string with the specified number of digits behind the decimal point
parseFloat() Parse a string and return a floating point number
parseInt() Parse a string and return an integer
Number("99, 88")   / / returns NaN

var y = "5";      // y is a string
var x = + y;      // x is a number

var y = "John";   // y is a string
var x = + y;      // x is a number (NaN)
Copy the code

Different numeric values are converted to numbers, strings, and booleans

3. Typeof — tests the data typeof a variable

typeof "John"                // string
typeof 3.14                  // number
typeof false                 // boolean
typeof [1.2.3.4]             // object
typeof {name:'John'.age:34} // object
typeof new Date(a)/ / return the object
typeof function () {}         / / return function
typeof myCar                  // return undefined (if myCar is not declared)

typeof null                  // Represents an empty object reference,object
typeof undefined             // undefined
typeof NaN                    / / return number
Copy the code

The constructor property: Returns the constructors for all JavaScript variables

"John".constructor                 // Return function String() {[native code]}
(3.14).constructor                 Number() {[native code]}
false.constructor                  Boolean() {[native code]}
[1.2.3.4].constructor              // Return Array() {[native code]}
{name:'John'.age:34}.constructor  Object() {[native code]}
new Date().constructor             Date() {[native code]}
function () {}.constructor         Function(){[native code]}
Copy the code

You can use the constructor property to see if an object is an array

function isArray(myArray) {
    return myArray.constructor.toString().indexOf("Array") > -1;
}
Copy the code

4. Scope

Scope is a collection of accessible variables, objects, and functions.

  • Local scope: Variables are declared inside a function and can only be accessed inside the function. Local variables are created at the start of a function and destroyed automatically after the function is finished.
  • Global scope: Variables defined outside of functions are global variables that can be used by all scripts and functions in a web page. The global variable is the window object.

If a variable is not declared in a function (without the var keyword), it is a global variable.

// The carName variable can be called here
function myFunction() {
    carName = "Volvo";// A global variable that can be accessed using window.carname
    // The carName variable can be called here
}
Copy the code

5. Claim promotion

Function and variable declarations are promoted to the top of the function, and variables can be declared after use, i.e. variables can be used before declaration.

x = 5; // Set the variable x to 5
var x; / / declare x
Copy the code

Only declared variables are promoted, initialized ones are not.

console.log(y) // undefined
var y = 7 // Initialize y (var y is improved, but initialization (y = 7) is not)
Copy the code

In use strict mode, you can’t use undeclared variables. In strict mode, variables, objects and functions are not allowed to be deleted. Variable names are not allowed; Octal is not allowed; Escape characters are not allowed; Assignment to read-only attributes is not allowed, and so on.

6. Let and const (block-level scope)

ES2015(ES6) added let and const. Let declared variables are only valid within the code block in which the let command resides. Const declares a read-only constant that must be initialized and whose value cannot be modified.

Block-level scopes: Let and const implement block-level scopes that are valid only within the code block {} and cannot be accessed outside {}.

var x = 10;// output x is 10
{ 
    let x = 2;// output x is 2
}
// output x is 10
Copy the code

Loop scope: The variables declared by var are global, including in and out of circulation; The scope of variables declared by LET is only in the circulatory body, and variables outside the circulatory body are not affected.

var i = 5;
for (var i = 0; i < 10; i++) {}
// output I is 10

let i = 5;
for (var i = 0; i < 10; i++) {}
// output I is 5
Copy the code

Window object: The global scope variable declared by the var keyword belongs to the window object; The global scope variable declared by let does not belong to the Window object.

Nature of const: A variable defined by const is not a constant immutable. It defines a constant reference to a value. Objects or arrays defined by const are mutable.

const car = {type:"Fiat".model:"500".color:"white"};// // Create a constant object
car.color = "red";// Modify attributes
car = {type:"Volvo".model:"EX60".color:"red"};    / / error


const cars = ["Saab"."Volvo"."BMW"];// Create an array of constants
cars[0] = "Toyota";// Modify the element
cars.push("Audi");// Add elements
cars = ["Toyota"."Volvo"."Audi"];    / / error
Copy the code

You cannot use the let keyword to reset a variable declared by the var keyword. Variables declared by let and const cannot be promoted;

Regular expressions

Regular expressions use a single string to describe and match a series of string search patterns that conform to a syntactic rule.

/ / grammar/ Regular expression body/modifier (optional)var patt = /runoob/i // Runoob is a regular expression body (for retrieval), and I is a modifier (search is case-insensitive)
Copy the code
The modifier describe
i Case insensitive
g Global matching (find all matches instead of stopping after finding the first match)
m Multi-line matching
expression describe
[abc] Find any character between square brackets
[0-9] Find any number from 0 to 9
Vertical bar y (x) Look for any options separated by a vertical line
quantifiers describe
n+ Matches any string that contains at least one n
n* Matches any string containing zero or more n’s
n? Matches any string containing zero or one n
metacharacters describe
\d Find the number
\s Finding whitespace characters
\b Matching word boundaries
\uxxxx Finds Unicode characters specified in hexadecimal XXXX
  • Search () : Retrieves the substring specified in the string, or the substring matching the regular expression, and returns the starting position of the substring
var str = "Visit Runoob!"; 
var n = str.search(/Runoob/i); / / 6
Copy the code
  • Replace () : Replace some characters in a string with other characters, or a substring that matches the regular expression
var txt = str.replace(/microsoft/i."Runoob"); 
Copy the code
  • Test () : Tests whether a string matches a pattern, returning true if the string contains matching text, and false otherwise
/e/.test("The best things in life are free!")
Copy the code
  • Exec (): Used to retrieve a match for a regular expression in a string. This function returns an array containing the matching results. If no match is found, the return value is null
/e/.exec("The best things in life are free!");
Copy the code

This keyword

This represents a reference to the current object. This is not fixed in JavaScript; it changes as the execution environment changes.

The execution environment object
methods The object to which the method belongs
Used alone Global object
function Global object. In strict mode, this is undefined (undefined)
The event The element that receives the event
Call (), the apply () Reference this to any object

Explicit function binding

Call () and apply() allow you to switch the context in which the function executes, that is, the object bound to this.

var person1 = {
  fullName: function() {
    return this.firstName + "" + this.lastName; }}var person2 = {
  firstName:"John".lastName: "Doe",
}
person1.fullName.call(person2);  // return "John Doe"
Copy the code

Four, asynchronous

  • Synchronization: Synchronization does not mean that all steps are run at the same time, but that the steps are executed sequentially in a sequence of control flows;
  • Asynchronous: Synchronization is not guaranteed and the execution is no longer sequentially related to the original sequence. Asynchrony is sending a child thread from the main thread to complete a task.

  • Asynchronous usage scenarios:

Child threads are used to do things that take long enough for the user to notice, such as reading a large file or making a network request. The child thread is independent of the main thread, and blocking does not affect the main thread. However, once a child thread is fired, it loses synchronization with the main thread and cannot determine whether it is finished or not. If it is finished and needs to do something, such as processing information from the server, it cannot be merged into the main thread.

To solve this problem, asynchronous manipulation functions in JavaScript often implement the result processing of asynchronous tasks through callback functions.

  • Callback function:

Start an asynchronous task by telling it what to do when you complete it. This way the main thread hardly cares about the status of the asynchronous task, and it will finish the task itself.

function print() {
    document.getElementById("demo").innerHTML="RUNOOB!";
}
setTimeout(print, 3000);// print is a callback function
Copy the code

Five, the Promise

Promise is a class provided by ECMAScript 6 to make writing complex asynchronous tasks more elegant.

The Promise constructor takes only one function argument and is run asynchronously directly after construction, so we call it the starter function. The start function takes two arguments, resolve and reject. Resolve and Reject are functions, where resolve is called to indicate that everything is okay, and Reject is called when an exception occurs.

The Promise class has.then().catch() and.finally() methods. The arguments are all functions..then() adds the function from the argument to the normal execution sequence of the current Promise. .catch() is the exception handling sequence that sets the Promise, and.finally() is the sequence that must be executed at the end of the Promise execution.

new Promise(function (resolve, reject) {
    var a = 0;
    var b = 1;
    if (b == 0) reject("Divide zero");
    else resolve(a / b);
}).then(function (value) {
    console.log("a / b = " + value);// a / b = 0
}).catch(function (err) {
    console.log(err);
}).finally(function () {
    console.log("End");// End
});
Copy the code

Resolve () and return are used to pass a value to the next THEN. However, if a Promise object is returned in then, the next THEN will act on that returned Promise.

  • Resolve and reject are scoped only by initial functions, excluding THEN and other sequences.
  • Resolve and reject do not stop the initial function, and don’t forget return.
new Promise(function (resolve, reject) {
    console.log(1111);/ / 1111
    resolve(2222);
}).then(function (value) {
    console.log(value);/ / 2222
    return 3333;
}).then(function (value) {
    console.log(value);/ / 3333
    throw "An error";
}).catch(function (err) {
    console.log(err);//An error
});
Copy the code

Asynchronous functions

Async function is a specification of the ECMAScript 2017 standard. An await instruction must be followed by a Promise, and the async function will pause in the Promise execution until it is finished.

async function asyncFunc() {
    await print(1000."First");
    await print(4000."Second");
    await print(3000."Third");
}
asyncFunc();
Copy the code

Asynchronous functions work exactly as the Promise native API does, with exception handling implemented in try-catch blocks:

async function asyncFunc() {
    try {
        await new Promise(function (resolve, reject) {
            throw "Some error"; // 或者 reject("Some error")
        });
    } catch (err) {
        console.log(err);
        // Outputs Some error
    }
}
asyncFunc();
Copy the code