javascript

The data type

The data type

  • Basic types:number / string / boolean / undefined / null / symbol
  • Reference type:object / array / function

Data type detection

typeof

  • string number boolean object undefined function symbol
  • The null Object array cannot be distinguished

instanceof

  • Instanceof determines data types through a chain of stereotypes.
  • [] instanceof Array
  • Let STR = new String(‘test’); str instanceof String

Object.prototype.toString.call()

  • ToString method on the Object prototype chain.
  • Return to [object type]
  • [object Number / String / Object / Array / Undefined / Null / Boolean]

Deep copy and shallow copy

Shallow and deep copies are for reference types only, such as Object/ array /function.

A shallow copy copies only one level of the object’s properties, while a deep copy copies all of the object’s property levels. If you change the reference type value of the initial value, the value of the shallow copy will change, and the value of the deep copy will not change.

Shallow copy

  • Object.assign(obj)

Deep copy

  • Parse (json.stringfy (obj)) => Function properties on the object will not be copied to the new object.
  • {… Obj} => All base and reference types can be copied.

Js implements a deep copy

function clone(source){
    // If the source object is null, null is returned
    if(!typeof source === 'object'|| source === null) return source;
    // Non-reference source data, such as strings and numbers, booleans, are returned directly.
    if( typeofsource ! = ='object' ) return source;
    // Determine whether the source data is an object or an array, and then distinguish between assignments. Array.isArray
    let target = Array.isArray(source) ? [] : {};
    // Get the names of all the properties of the object or the subscripts of the array
    for (const key in source) {
        // Determine if the property is private
        if (source.hasOwnProperty(key)) {
            const el = source[key];
            // If the value is a reference type, continue to iterate
            if( typeof el === 'object'){
                target[key] = clone(source[key]);
            }else{
                // Otherwise, it is assigned to a new objecttarget[key] = source[key]; }}};return target;
}
Copy the code

scope

Variable declaration promotion

  • Variables and functions declared by var are promoted to the top of the JS code.
  • Just promote the variable, assignment does not promote, printing before its declaration will print undefined.
  • Const and let variables and constants do not raise the variable declaration.
  • Function declarations take precedence over variable declarations. If there are functions and variables with the same name, the function overrides the variable if the variable is not assigned a value.

The scope chain

  • Because the nested function, and the scope of the hierarchy, the function, that variable if used in the current function scope is not found, will be to the higher level functions within the scope of the search, if not, then continue up, until find the global scope window, this is the scope chain.

closure

  • Closures link the inside of a function with the outside of a function, allowing variables inside the function to be used outside the function.
  • Keep these variables in memory all the time.
  • A function is thrown inside a function that uses a variable inside the function. A function that is thrown is received externally. Variables declared inside the function are not released and remain in memory.
function outer(){
    let num = 100;
    return function inner(){
        console.log( num ++ ); }};let func = outer();

func();
func();
Copy the code

Archetypes and inheritance

Js creates objects in several ways

  • let obj = {};
  • let obj = Object.create({a: 1});
  • let obj = new Object();

How does JS implement a class

  • The constructor

    // Use prototype
    function Person(name, age){
        this.name = name;
        this.age = age;
        this.showName = () = > {
            console.log( this.name ); }}; Person.prototype.showInfo =function(){
        return this.name + The '-' + this.age
    }
    Copy the code
  • Class(ES6 Grammar Sugar)

    class Person{
        constructor(name, age){
            this.name = name;
            this.age = age;
            this.showName = () = > {
                console.log( name ); }};showInfo(){
            return this.name + The '-' + this.age
        }
    }
    Copy the code

Prototype chain

  • When we use an attribute on an object, we look for the attribute in the object itself, and if we can’t find it, we follow the implicit stereotype of the object__proto__Go up layer by layer until you find NULL. This article is made up of__proto__The resulting chain is the prototype chain.
  • prototype __proto__ constructor new

inheritance

How does JS implement inheritance

  • Object.create(obj, {})
  • {}.__proto__ = prototype
  • new Constructor | class
  • Object.setPrototypeOf(obj, prototype)

New and this

What does the new operator do

  1. Create an instance object {}
  2. Point this to the instance object that inherits the stereotype of the constructor
  3. Properties and methods are then added to the object referenced by this.
  4. The newly created object is referred to by this, and this is implicitly returned.

A simulated implementation of new

Understanding this object

  • This always refers to the direct caller of the function
  • In normal functions, this refers to the window.
  • In the arrow function, this points to the parent scope.
  • For constructors, this refers to the instance of the call.

Call, apply, and bind

  • It’s all about changing the function’s this point to the problem.
  • call(this, p1, p2, … ) , will execute the function immediately, can pass multiple arguments.
  • bind(this, p1, p2, … ) , does not execute the function immediately and can pass multiple arguments.
  • apply(this, [p1, p2, …] ), the argument passed is an array format

The data processing

Data to heavy

let arr = [1.2.3.4.5.6.7.2.3.4.7.8.9.7];
// es6 Set & Array.from()
let set = new Set(arr);
Array.from(set);
// map & includes & push
function counterSingle (list) {
    let _list = [];
    list.map( i= >! _list.includes(i) && _list.push( i ) );return _list;
}
counterSingle(arr);
Copy the code

Data sorting

let arr = [1.2.3.4.5.6.7.2.3.4.7.8.9.7];
// api
arr.sort( (a, b) = >  a -b );
/ / rewrite
function arraySort(arr){
    for( var i = 0; i < arr.length; i ++ ){
        for( var j = i + 1; j < arr.length; j ++ ){
            if( arr[i] > arr[j] ){
                lettemp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }}};return arr;
};
arraySort(arr);
Copy the code

Recursion sum

let arr = [1.2.3.4.5.6.7.2.3.4.7.8.9.7];
let number = 100;
let num = arr.reduce((acc, cur) = > acc + cur );
console.log( num );

let totalNumber = 0;
for( var i = 0; i <= number;  i++ ){
    totalNumber += i;
};
console.log( totalNumber );
Copy the code

Recursive quadrature

function multiple (number) {
    return number * (number === 1 ? 1 : multiple( number - 1 ));
}
console.log( multiple(5));
Copy the code

Count the number of repetitions of items in the array

let arr = [1.2.3.4.5.6.7.2.3.4.7.8.9.7];
// Count the number of repeats
let obj = {};
for (const value of arr) {
    obj[value] ? obj[value] ++ : obj[value] = 1;
};
console.log( obj ); 
Copy the code

Fibonacci numbers

function fbnq(len){
    let list = [ 1.1 ];
    for( var i = 1; i < len - 1; i ++){
        list.push( list[i] + list[ i - 1]); };return list;
};

fbnq(10);
Copy the code

Maximum array difference

// Math
maxDiffer = () = > {
    let list = [20.40.123.123.34.45.454.30];
    let max = Math.max( ... list );let min = Math.min( ... list );return max - min;
}
/ / handwriting
maxDiffer = () = > {
    let list = [20.40.123.123.34.45.454.30];
    let max = list[0];
    let min = list[0];
    for( var i = 1; i < list.length; i ++ ){
        if( list[i] > max ){
            max = list[i];
        }
        if( list[i] < min ){ min = list[i]; }}return max - min;
}

console.log( maxDiffer() )
Copy the code

Event Loop

Heap, stack, queue

  • Heap: Data structure, a set of data maintained using a full binary tree.
  • Stack: is a linear table that followsAfter the advancedThe principle of insertion and execution from the tail.
  • Queue: FollowFirst in first outThe principle of insert from the tail of the table, delete from the head.
  • Js execution stack: JS is a single-threaded language. It has a main thread and a call-stack. All the main thread tasks are placed in the execution station to wait for the main thread to execute.

Macro and micro tasks

  1. Macro task: All tasks executed in the current call stack are called macro tasks, including script code, settTimeout, setInterval, etc.
  2. Micro-task: After the macro task is completed, the next task to be executed is called a micro-task, including promise, async/await, etc.
  3. Tasks of different types are placed in the Event Queue, macro tasks are placed in the callback Queue, and events trigger thread maintenance. Microtasks are placed in a microtask queue, which is maintained by the JS engine thread.

What is an Event loop

  • Js is a single thread, its multithreading and asynchronous is by the event loop (event polling) to achieve.
  • Js parses the methods from top to bottom, placing the synchronization tasks in the execution order on the execution stack.
  • When a program calls an external API (such as Ajax or setTimeOut), it suspends the asynchronous task, puts it on a message queue, and continues executing the task in the execution stack. Promises and async/await are placed in the microtask queue.
  • After the execution of the main thread, the system first checks whether there are any tasks in the microtask queue. If so, the system will execute them immediately. All microtasks encountered in the execution process will also be executed synchronously.
  • The task in the message task is executed when the microtask queue is completed or when the microtask queue is not empty. If an asynchronous task is encountered during execution, it continues to be placed in the message queue.
  • Methods and programs are ejected from the execution station after they have finished executing.
  • Each time the main thread empties the execution station, it checks the Event queue to see if there are any tasks that need to be executed. If there are any tasks, it takes one out and puts it on the execution stack. The process of this Loop is called the Event Loop.

Browser page rendering process

  1. The browser parses the HTML code and creates a DOM tree. Parallel requests CSS, JS, and IMG.
  2. The browser parses the CSS code and computes the final style data to create a cssDOM rendering tree.
  3. CSS priority: CSS in HTML > Inline style > External Style > User Settings > Browser Default Style
  4. Once the render tree is created, the browser draws the page on the screen based on the results of the render tree.
  5. CSS and JS tend to modify the DOM and CSSDOM multiple times.
  • Dom trees differ from render trees: Render trees have styles, and nodes such as display: None are removed from the render tree.

Browser cache

Browser cache awareness

  1. Strong cache
    • The main use of Expires and cache-Control fields is to read the local Cache file without sending a request to the browser.
    • A Expires is a point in time that depends on the client’s time, after which a cached resource Expires and a request is sent to the server.
    • Cache-control is a relative time in which you can set max-age to expire in seconds. It also has a higher priority than Expires.
  2. Negotiate the cache
    • The server determines whether the cache resources are available, and the server and client need to work together to use the cache resources.
    • The server returns last-Modified and ETag fields in the Response header.
    • Last-modified indicates the time when the resource was last modified on the server. If the resource is requested again, the request header will be if-modified-since, asking whether the resource has been updated.
    • Each time the file is modified, the server generates a new ETag. When the resource is requested again, the browser’s request header contains if-none-match, which is the value of the ETag returned earlier. If the ETag has changed, the resource needs to be updated.

Common front-end caching

  1. cookie

    • Storage in the client, there is a size limit, about 4KB.
    • You can set expiration events, default browser closed time.
  2. Session

    • Storage in the server, relatively secure.
  3. SessionStorage

    • Local storage on the client, which is cleared when the browser closes. Size is 5 MB
  4. LocalStorage

    • Local storage on the client. If you do not manually clear the storage, it will always be saved in the browser.

css

The box model

  • The box model from inside to outside are content, padding, border and margin
  • In Ie, width = content + padding + border
  • In the standard box model: width = content
  • Box – sizing: border – box | content – box (the default)

In the middle

Horizontal center

  • Text-align: center;
  • Block elements: margin: 0 auto;
  • position: relative; left: 50%; transform: translateX( -50% )
  • display: flex; justify-content: center

Vertical center

  • position: relative; top: 50%; transform: translateY(-50%);
  • display: flex; align-items: center;
  • height: 100px; line-height: 100px;