2020 interview preparation collection

Time:2021-9-15

First list the questions, then add the answers.

JS

1. Eventloop

It is mainly divided into three parts: main thread, macro task and micro task
Main thread, that is, the contents contained in the accessed script tag, or all the contents that can be executed directly in the current scope when directly accessing a JS file (execution methods, new objects, etc.)
Macro queue(macrotask), setTimeout, setinterval, setimmediate, UI rendering, etc
Microqueue(microtask), promise.then, mutaionobserver, process.nexttick, etc
Execution sequence
First execute the main thread, put macro tasks into macro queue and micro tasks into micro queue (microtask. After the main thread is executed, the call stack is cleared. At this time, the callback in the first place will be taken from the micro queue and put into the execution stack for execution. The length of the micro queue is – 1, and then the callback tasks in the queue will be executed successively until all tasks are executed. At this time, the micro queue is empty and the call stack is empty. At this time, the callback in the first place will be taken from the macro queue Then put it into the call stack for execution. After execution, go to get the tasks in the micro queue and cycle according to the previous steps.

2. Why should JS be implemented as a single thread and what are the benefits?

reason:As a browser scripting language, JavaScript is mainly used to interact with users and manipulate dom. This determines that it can only be a single thread, otherwise it will bring very complex synchronization problems.
Benefits of single threadingImagine that if JavaScript is designed as a multithreaded program, the operation of DOM will inevitably involve resource competition, and the language will be very bloated. Running a program in such a language on the client will not be optimistic about resource consumption and performance. At the same time, it is not just necessary to implement multithreading on the client.
If it is designed as a single thread and supplemented by a perfect asynchronous queue, the running cost will be much smaller than that of multi-threaded design.

3. Differences between processes and threads

  1. Process is the smallest unit of resource allocation, and thread is the smallest unit of program execution (the smallest unit of resource scheduling)
  2. A process has its own independent address space. Every time a process is started, the system will allocate address space for it and establish a data table to maintain code segments, stack segments and data segments. This operation is very expensive.
    Threads share the data in the process and use the same address space. Therefore, the cost of CPU switching a thread is much less than that of the process, and the cost of creating a thread is much less than that of the process.
  3. The communication between threads is more convenient. Threads in the same process share global variables, static variables and other data, and the communication between processes needs to be carried out in the way of communication (IPC). However, how to deal with synchronization and mutual exclusion is the difficulty of writing multithreaded programs.
  4. However, multi-process programs are more robust. As long as one thread of multi-threaded programs dies, the whole process also dies, and the death of one process will not affect another process, because the process has its own independent address space.

4. Meaning, principle, advantages and disadvantages, usage scenario and how to recycle closures

meaning:A closure is a combination of a function and the Lexical Environment in which it is declared. This environment contains all local variables that can be accessed when the closure is created.
A closure is a function that can access variables in the scope of other functions. It is a bridge between the inside and outside of a function.
Principle:The scope of a function is a scope chain, and the scope chain is sequential. We call it chain scope structure. In JS, the external cannot read the internal variables, but the internal can read the external variables. Using this feature, closures can throw the read properties for external use.
advantage:You can read variables inside the function and keep the values of these variables in memory all the time.
Disadvantages:Closures have a negative impact on script performance and should not be abused. And the closure will change the value of the internal variable of the parent function outside the parent function.
Usage scenario:

  1. Set private variables to objects and use privileged methods to access private properties
  2. When calling setTimeout by function reference, the first function passed by the native setTimeout cannot take parameters, and the parameter passing effect can be realized through closure
  3. The implementation of singleton mode ensures that there is only one instance object in the world
  4. Module imitates modularity and uses closures to encapsulate “private” state and organization. Only one public API is returned, and all other rules are in private closures to prevent disclosure to the global scope, and reduce conflicts with other developers’ interfaces.

5. What are the JS data types and how to judge them?

Basic types: string, number, Boolean, null, undefined, symbol, bigint
Complex type: object

Common basic types: undefined, null, symbol
Special basic packing types: string, number, Boolean

Reference type: object, data, function, array

Judgment method:

  1. typeof
  2. instanceof
  3. Object.prototype.toString.call(data)

6. What are the types of conversion?

  1. To string: tostring(), string(), splicing empty characters
  2. To Boolean: boolean(),! (),!! ()
  3. To number: number(), parseint(), + data

7. Execution context

Execution context is an abstract concept of the environment in which JavaScript code is evaluated and executed. Whenever JavaScript code is running, it runs in the execution context.
There are three types of execution context in javascript:
Global execution context– this is the default or basic context. Any code not inside the function is in the global context. It does two things: create a global window object (in the case of a browser) and set the value of this equal to the global object. There will only be one global execution context in a program.
Function execution context– whenever a function is called, a new context is created for the function. Each function has its own execution context, but it is created when the function is called. There can be any number of function contexts. Whenever a new execution context is created, it executes a series of steps in the defined order.
Eval function execution context– code executed inside the eval function will also have its own execution context.

Creating an execution context is divided into two phases:1. Creation phase   2. Implementation phase

Three things happen during the creation phase:

  1. The decision of this value, which is known as this binding.
  2. Create a lexical environment component.
  3. Create a variable environment component.

8. What does the new operator do

  1. Create an empty objectvar o=new Object();
  2. Assign the prototype of an empty object to the prototype of constructor ao.__proto__=A.prototype;
  3. Execute the code in the constructor to add properties to the empty objectA.call(o);, it can also be understood as pointing this inside the constructor function to the newly created empty object.
  4. Returns the object after adding the property.
function New(obj){ 
    var o = new Object(), 
        Constructor = obj; 
    o.__proto__ = Constructor.prototype; 
    Constructor.call(o); 
    return o; 
}

9. Explain the relationship among constructor, object and prototype chain

Each constructor has a prototype object. The prototype object contains a pointer to the constructor, and the instance contains an internal pointer to the prototype object. Generally speaking, the instance can access the prototype object through the internal pointer, and the prototype object can find the constructor through the constructor.

10. Several ways of inheritance and their advantages and disadvantages

  1. Prototype chain inheritance
    Disadvantages: the attribute of reference type is shared by all instances; When creating an instance of child, you cannot pass parameters to the parent

    function Parent () {
        this.names = ['11', '22'];
    }
    function Child () {}
    Child.prototype = new Parent();
    var child1 = new Child();
    child1.names.push('33');
    console.log(child1.names); // ["11", "22", "33"]
    var child2 = new Child();
    console.log(child2.names); // ["11", "22", "33"]
  2. Constructor inheritance
    Advantages: the attribute of reference type is avoided to be shared by all instances, and parameters can be passed to parent in child
    Disadvantages: all methods are defined in the constructor, and the method will be created every time an instance is created.

    function Parent (name) {
        this.name = name;
    }
    function Child (name) {
        Parent.call(this, name);
    }
    var child1 = new Child('11');
    console.log(child1.name); // 11
    var child2 = new Child('22');
    console.log(child2.name); // 22
  3. Combinatorial inheritance
    Advantages: integrating the advantages of prototype chain inheritance and constructor, it is the most commonly used inheritance mode in JavaScript
    Disadvantages: call the constructor of the parent twice

    function Parent (name) {
        this.name = name;
        this.colors = ['red', 'blue', 'green'];
    }
    Parent.prototype.getName = function () {
        console.log(this.name)
    }
    function Child (name, age) {
        Parent.call(this, name);
        this.age = age;
    }
    
    Child.prototype = new Parent();
    var child1 = new Child('kevin', '18');
    child1.colors.push('black');
    console.log(child1.name); // kevin
    console.log(child1.age); // 18
    console.log(child1.colors); // ["red", "blue", "green", "black"]
    
    var child2 = new Child('daisy', '20');
    console.log(child2.name); // daisy
    console.log(child2.age); // 20
    console.log(child2.colors); // ["red", "blue", "green"]
  4. Prototype inheritance

    function createObj(o) {
        function F(){}
        F.prototype = o;
        return new F();
    }

    Disadvantages: attribute values containing reference types always share corresponding values, which is the same as prototype chain inheritance.

  5. Parasitic Inheritance
    Disadvantages: like borrowing the constructor pattern, the method is created every time an object is created

    function createObj (o) {
        var clone = object.create(o);
        clone.sayName = function () {
            console.log('hi');
        }
        return clone;
    }
  6. Parasitic combinatorial inheritance
    Advantages: the efficiency of this method shows that it only calls the parent constructor once, and therefore avoids creating unnecessary and redundant attributes on the parent.prototype. At the same time, the prototype chain can remain unchanged; Therefore, instanceof and isprototypeof can also be used normally. Developers generally believe that parasitic composite inheritance is the most ideal inheritance paradigm for reference types.

    function object(o) {
        function F() {}
        F.prototype = o;
        return new F();
    }
    
    function prototype(child, parent) {
        var prototype = object(parent.prototype);
        prototype.constructor = child;
        child.prototype = prototype;
    }

11. Prototype inheritance

function createObj(o) {
    function F(){}
    F.prototype = o;
    return new F();
}

12. Implement constructor inheritance

function Parent (name) {
    this.name = name;
}
function Child (name) {
    Parent.call(this, name);
}
var child1 = new Child('11');
console.log(child1.name); // 11
var child2 = new Child('22');
console.log(child2.name); // 22

13. Object oriented attributes

Polymorphism, encapsulation, inheritance

14. What are the design patterns and what are used in the project

  1. Singleton mode, reference vuex, loading, global pop-up window, etc
  2. Policy mode, encapsulate different calculation methods, encapsulate call interfaces, and calculate commodity prices of common shopping carts
  3. For observer mode, refer to the call of webpack internal plugin
  4. Publish subscribe mode, refer to Vue responsive principle
  5. Iterator pattern, refer to foreach, map method, extended iterator

15. What are the processes of browser events? Why do you usually register listening in the bubbling phase rather than in the capture phase? What are the addeventlistener parameters?

Process:Event capture phase, target phase, bubble phase

Ie does not support capture in lower versions. For compatibility, it is generally written bubbling

addEventListenerThree parameters are acceptable: the name of the event to be processed, the function as the event handler, and a Boolean value. If the Boolean value is true, it means that the event handler is called in the capture phase; If false, it means that the event handler is called in the bubbling phase

16. Is new string (‘a ‘) the same as’ a’?

Let data = 'a' // defines a basic type character creation and stacking
Let data = new string ('a ') // defines a packing type string, which is put into the heap,

17. Do you understand the packing and unpacking in JS?

Packing:The operation of converting a basic data type to a corresponding reference data type. Whenever a basic type is read, a corresponding basic wrapper type object will be created in the background, so that we can call some methods to manipulate the data.
Therefore, directly defining a basic type string can also call methods.

var s1 = "abc";
var s2 = s1.indexOf("a")

Unpacking:Converts a reference type object to a corresponding value type object
If it is a custom object, you can also customize itsvalueOf()perhapstoString()Method to unpack this object.

var objNum = new Number(123);  
 var objStr =new String("123");   
 console.log( typeof objNum ); //object
 console.log( typeof objStr ); //object 
 console.log( typeof objNum.valueOf() ); //number
 console.log( typeof objStr.valueOf() ); //string  
 console.log( typeof objNum.toString() ); // string 
 console.log( typeof objStr.toString() ); // string

18. Throttling and anti shake principle

Anti chattering and throttling function is one of the most commonly used high-frequency trigger optimization methods, which can be of great help to the performance.

Debounce: multiple high-frequency operations are optimized to be executed only at the last time. The usual scenario is: user input. Only one input verification is required after input is completed.

function debounce(fn, wait, immediate) {
    let timer = null
    return function() {
        let args = arguments
        let context = this
        if (immediate && !timer) {
            fn.apply(context, args)
        }
        if (timer) clearTimeout(timer)
        timer = setTimeout(() => {
            fn.apply(context, args)
        }, wait)
    }
}

Throttle: execute every other period of time, that is, reduce the frequency and optimize the high-frequency operation into low-frequency operation. Usually, use the scenario: scroll bar event or resize event, which can be executed every 100 ~ 500 ms.

function throttle(fn, wait, immediate) {
    let timer = null
    let callNow = immediate
    return function() {
        let context = this,
            args = arguments;
        if (callNow) {
            fn.apply(context, args)
            callNow = false
        }
        if (!timer) {
            timer = setTimeout(() => {
                fn.apply(context, args)
                timer = null
            }, wait)
        }
    }
}

19. What is the difference between object-oriented and non object-oriented

Object oriented is the abstraction of event processing, which is convenient for extended design. Non object-oriented is generally aimed at process processing, and there is no abstract concept.

20. What is a higher-order function and how to write a higher-order function

It only needs to meet any of the following conditions, that is, it is a higher-order function:

  1. Accepts one or more functions as input
  2. Return returns another function

21. Modularity. What is compile time optimization? Modular evolution?

Amd / CMD / ES6 modules are mainly used for front-end, and they all belong to asynchronous parallel loading

AMD is a dependency prefix. First define the dependency module in define, and then make a reference in the callback function

CMD is a post dependency. It defines a module. When is the module used and when is the module required

Commonjs generally runs on the node side. Copy the attribute module.exports, and then use require to copy the attribute module.exports. The required module is loaded synchronously, and the required module is the copy value, which will not change the reference module. The import we wrote in webpack was finally converted into commonjs

ES6 module is export and import, but export is an interface. Import only uses the interface to reference its content, so the content can be modified. Commonjs require is a dynamic compilation, which is loaded at runtime, and import is a static compilation. However, at present, there is an import () function in the proposal, which can realize dynamic loading. In addition, there is an updated proposal, await promotion. Previously, await can only be used in functions marked async. The current proposal is that await can be used alone. During dynamic loading of import (), then needs to be written for subsequent processing. Now it is not used, and the writing method is much simplified.

22. Briefly talk about PWA

PWA does not only refer to a certain technology. You can understand it as an idea and concept. The purpose is to benchmark the native app, optimize the web site through a series of web technologies, improve its security, performance, fluency, user experience and other indicators, and finally achieve the feeling that users feel like using an app.

The core functions and features included in PWA are as follows

  1. Web App Manifest
  2. Service Worker
  3. Cache API cache
  4. Push & notification push and notification
  5. Background sync background synchronization
  6. Responsive design

23. Implementation of call / apply / bind principle

call

Function.prototype.mycall = function(context) {
    //This points to the function object calling mycall. If it is not a function, an error will be reported
    if (typeof this !== 'function') {
        throw new TypeError('Not Function')
    }
    //If the context is null, undefined or not passed, it points to the window
    context = context || window
    //Add the function object calling mycall to the property of context
    context.fn = this
    //Get the parameters other than the first parameter, and then execute
    const args = [...arguments].slice(1)
    //This of the mycall function object points to the context
    const result = context.fn(...args)
    //Delete the attribute
    delete context.fn
    return result

}

apply

Function.prototype.myapply = function(context) {
    if (typeof this !== 'function') {
        throw new TypeError('Not Function')
    }
    if (arguments[1] instanceof Array) {
        throw new TypeError('Arguments Need To Array')
    }
    context = context || window
    context.fn = this
    let result = null
    //If no parameters are passed, the arguments [1] is undefined, and the deconstruction will report an error
    if (arguments[1]) {
        result = context.fn(...arguments[1])
    } else {
        result = context.fn()
    }
    return result
}

bind

Function.prototype.mybind = function(context) {
    if (typeof this !== 'function') {
        throw new TypeError('Not Function')
    }
    context = context || window
    const originFunc = this
    const args = [...arguments].slice(1)
    return function() {
        //When the handler becomes a constructor
        //The new. Target attribute allows you to detect whether a function is called through the new operator. In normal function calls, the value of new. Target is undefined
        if (new.target) {
            //If the constructor return is a reference value, the new operator returns the reference value
            return new originFunc(...args, ...arguments)
        } else {
            return originFunc.call(context, ...args, ...arguments)
        }
    }
}
  1. What are the ways to manipulate DOM?
  2. How to use native JS to realize a rotation chart and scroll and slide?
  3. How to realize the function of uploading and downloading?
  4. What are the methods of map?
  5. Do you know about pseudo array objects?

29. How to read and write cookies with native JS?

const cookieArray = document.cookie;  // Get cookie store string 
const arr = cookieArray.split(";");   // Set the obtained cookie string to; Separate each cookie name / value pair

//Read
//Assuming that the name of the cookie to be obtained is name, traverse the array to find the value corresponding to the name  
let result = ''
for(var i=0;i<arr.length;i++){  
  var arr1 = arr[i].split("=");     // Split name / value pairs with "="  
  if(arr1[0]==name){  
    result = arr1[1];  // If the name is name, the result is the value corresponding to the name  
  }
}
//Set
document.cookie="name=value;expires=GMT_String";

30. Local storage

31. How to break points and determine which function a result comes from

debugger

32. Briefly describe the implementation method of user-defined events

33. Parameters of the map method of parseint() and array

34. Deep cloning of JSON objects

35. Difference between objec.free and object.seal

36. Write the function convert (money), pass in the amount, and convert the amount into the thousandth representation

37. JS floating point number operation is not accurate. How to solve it

When we perform operations, we actually convert numbers into binary, so we convert 0.1 and 0.2 into binary:
0.1 = > 0.0001 1001 1001 1001.. (infinite loop)
0.2 = > 0.0011 0011 0011… (infinite loop)
It can be seen here that the conversion to binary is an infinite cyclic number,Only in the computer, if the number of infinite loop will be rounded, the decimal part of double precision floating-point number can support 52 digits at most. Then two binary numbers are calculated to obtain a binary value, and finally it is converted to decimal。 Keep 17 decimal places, so the value of 0.1 + 0.2 becomes 0.300000000000000 4.   The value of 0.1 + 0.1 becomes 0.2 billion. If it is all 0, it can be omitted and becomes 0.2.
The simplest solution is to directly ToFixed, and sometimes the result is inaccurate, so we can also directly intercept the value after the decimal point and directly multiply it by a multiple of 10 to obtain the addition result, and then divide it by the same multiple of 10.

38. Realize the coritization of functions

39. Front end storage methods and their advantages and disadvantages

40. How to find the desired node from 100000 nodes and how to quickly insert a node in front of a node?

41. How to find the two longest strings in a string?

42. Have you ever used it? Exec, match a phone number? Go to the space?

43. Give you 100 million numbers, which are continuous. How can you find two nonexistent numbers

44. How to implement a sleep and write a promise

45. How to make a table and refresh it once a minute

46. Do you understand the implementation principle of webworker and have you practiced it privately

Directly speaking, webworker can have multi-threaded operation turned on, but can’t operate dom. Multithreads can transmit information through PostMessage and listen to onmessages to obtain information.

47. Have you considered the problem of memory in your usual projects? How?

48. What are the asynchronous processing schemes?

array

1. What is the function of array’s unshift () method? How do I connect two arrays? How do I remove an element from an array?

2. Array de duplication

// set
function unique (arr) {
  return Array.from(new Set(arr))
}
// indexOf
function unique(arr) {
    if (!Array.isArray(arr)) {
        console.log('type error!')
        return
    }
    var array = [];
    for (var i = 0; i < arr.length; i++) {
        if (array .indexOf(arr[i]) === -1) {
            array .push(arr[i])
        }
    }
    return array;
}
// includes
function unique(arr) {
    if (!Array.isArray(arr)) {
        console.log('type error!')
        return
    }
    var array =[];
    for(var i = 0; i < arr.length; i++) {
            If (! Array. Includes (arr [i])) {// includes detects whether the array has a value
                    array.push(arr[i]);
              }
    }
    return array
}
// filter+indexOf
function unique(arr) {
  return arr.filter(function(item, index, arr) {
    //Current element, the first index in the original array = = the current index value, otherwise the current element is returned
    return arr.indexOf(item, 0) === index;
  });
}

3. Array disorder

function shuffle(arr) {
    let newArr = arr.map(item\=>({val:item,ram:Math.random()})); 
    newArr.sort((a,b)=>a.ram-b.ram); 
    let newArr = newArr.map(i=>i.val)
    return newArr; 
}
function shuffle(arr) { 
    let m = arr.length; 
    while (m > 1){ 
        let index = Math.floor(Math.random() * m--); 
        [arr[m] , arr[index]] = [arr[index] , arr[m]] 
    } 
    return arr; 
}

4. What sort algorithms are available and what is the time complexity? When is fast platoon the least efficient?

5. What are the methods of changing the array and not changing the array?

6. Given an array and a positive integer n, find the longest continuous subarray whose sum is less than n

7. Given two ordered arrays, merge them into one ordered array. Concat and sort methods of JS are not allowed

function arrSort(arr1, arr2) {
    var [i,j] = [0,0];
    let newArr = [];
    while(i < arr1.length || j <arr2.length) {
        if (arr1[i] < arr2[j]) {
            newArr.push(arr1[i]);
            i++
        } else if (arr1[i] > arr2[j]) {
            newArr.push(arr2[j])
            j++
        } else {
            if(arr1[i]) newArr.push(arr1[i]);
            if(arr2[j]) newArr.push(arr2[j]);
            i++;
            j++
        }
    }
    return newArr
}

8. Principle of sort()

**When the array length is less than or equal to 10, insert sorting is adopted, and when it is greater than 10, fast sorting is adopted.
For arrays with a length greater than 1000, the combination of fast sorting and insertion sorting is used for sorting, because when the amount of data is very small, the insertion sorting efficiency is better than fast sorting**

9. Do not generate a new array and delete the duplicate elements in the array

10. Difference between bubble sort and quick sort

Bubble sorting is to compare Du from the lowest element (compared with the elements on it). If it is less than, it will be compared upward, and if it is greater than, it will be exchanged. Then it will be compared upward with the smaller Dao until the highest level. For the first time, put the smallest on the top level, the second time put the second smallest on the second level, and so on.

Quick sorting is to find an axis value first. During comparison, put all smaller than the axis value to the left and larger than the axis value to the right, then select the axis values on both sides, and then sort according to the front until it is completed.

ES6

  1. Principle of promise
  2. ES6 module
  3. Let’s talk about the generator function
  4. Let’s talk about the understanding of async and await
  5. What are the methods of map?
  6. Arrow function, this points to
  7. Function of extender
  8. What are the new data types?
  9. What are the new data structures?
  10. The difference between let and VaR in ES6
  11. Explain the temporary deadband of ES6

http

1. Talk about Ajax request

2. Cross domain

The same origin policy leads to cross domain. Solutions: jsonp, nignx reverse proxy, CORS configuration (there will be a pre check request)

3. Page loading process (what happens after entering the URL?)

4. TCP three handshakes and four waves, congestion control

5. Difference between TCP and UDP

6. What fields do the HTTP request header and response header have?

7. SSL encryption principle

Asymmetric encryption

8. What is the difference between http / HTTPS / HTTPS 2?

9. Advantages of http2

10. Do you understand the 304 status code in HTTP? 100 and 307?

304 – extended to browser cache problem
100: continue extends to post requests
307: temporary redirection. The request body will not change

11. Process communication, named and anonymous pipes

In terms of implementation means, there are the following types of communication between processes:

  1. Anonymous pipeline (affinity process)
  2. Famous pipeline (unrelated)
  3. Message queue
  4. Shared memory
  5. Semaphore
  6. Socket socket

Anonymous pipeline:

Pipe anonymous pipes are used to communicate between processes with consanguinity.
1. Half duplex communication, data can only be transmitted in one direction at the same time, with fixed read end and write end.
2. It can only be used for interprocess communication with kinship (parent-child or common ancestor).
3. It is essentially a buffer in the kernel.
4. It has its own “synchronous mutual exclusion mechanism”, and only one process can read data.
5. The life cycle changes with the process.
6. The pipeline provides byte stream service.

name pipes

FIFO: named pipeline (also half duplex). Each FIFO has a path name associated with it, so as to allow unrelated processes to access the same FIFO

characteristic:

  1. Data can be exchanged between unrelated processes
  2. FIFO has a pathname associated with it. It exists in the file system in the form of a special device file.
  3. There will be a rush to read. If you write once, you have to read. No matter who reads, the data in it will be cleaned up
  4. Browser cache

13. What are the differences among cookies, sessions and tokens?

Cookies are generated by the server and stored in the client browser. They are easy to be hijacked and unsafe
Sessions are saved on the server side, and each session ID is unique. When the number of users is too large, it takes up server resources and is safer
How token works:
1. When the client requests for the first time, it sends user information to the server. The server signs the user information using hsa256 algorithm and key, and then returns the signature and data to the client as a token.
2. The server will no longer save the token, and the client will save the token.
3. When the client sends the request again, send the token to the server in the request information.
4. The server uses the same hsa256 algorithm and key to calculate the signature of the data again and compare it with the signature of the token
5. If it is the same, the server knows that the client has logged in, and vice versa.

Advantages of Token:
1. Stateless and extensible
2. Support mobile devices
3. Cross program call
4. Safety

  1. If the browser is closed and then opened, is the request still from cache?

15. Have you known about service worker?

A middleman role between the server and the browser. If a service worker is registered in the website, it can intercept all requests of the current website and make judgment (corresponding judgment program needs to be written). If it needs to send requests to the server, it will be transferred to the server. If it can directly use the cache, it will directly return to the cache and will not be transferred to the server. So as to greatly improve the browsing experience.

  • Based on web worker (an independent thread independent of JavaScript main thread, which will not block the main thread when performing operations that consume a lot of resources)
  • On the basis of web worker, the ability of offline cache is added
  • Essentially, it acts as a proxy server between the web application (server) and the browser (it can intercept the requests of the whole site and make corresponding actions – > actions specified by the developer)
  • Create an effective offline experience (cache some infrequently updated content in the browser to improve the access experience)
  • Event driven with lifecycle
  • You can access cache and indexdb
  • Support push
  • It also allows developers to control and manage the content and version of the cache
  • Service worker runs in worker context — > cannot access DOM
  • It is designed to be completely asynchronous, and synchronous APIs (such as XHR and localstorage) cannot be used in service worker
  • For security reasons, service workers can only be hosted by HTTPS
  1. Why can token be used to prevent CSRF attacks?
  2. What is the refresh mechanism of token and why?
  3. How to implement browser caching of static files

19. What are the methods and what do they mean? What is the difference between post and put? What is the difference between post and get?

method
get Query data
post Generally, it is used to change the data of the server. It is often used for data submission and addition
put Like post, put requests will change the data of the server, but put focuses on the modification of data, while post focuses on the increase of data
patch Put updates are all updates. Patch can perform partial updates and only update the received data
delete The resource used to delete the server
options For the pre check request of the browser, check whether the server accepts the request. After the pre check is passed, the browser will send get, post, put, delete and other requests. Non simple requests are sent

What is the difference between post and put?
Like post, put requests will change the data of the server, but put focuses on the modification of data, while post focuses on the increase of data

What is the difference between post and get?

  1. Get is to get data from the server, and post is to transfer data to the server.
  2. Parameter transmission methods are different. One parameter is hung on the URL and one parameter is in the request body.
  3. The amount of data transferred by get is small and cannot be greater than 2KB. The amount of data transferred by post is large, which is generally unlimited by default. But theoretically, the maximum amount is 80Kb in iis4 and 100kb in iis5.
  4. Get generates one TCP packet and post generates two TCP packets. For the get request, the browser will send the HTTP header and data together, and the server will respond 200 (return data); For post, the browser sends the header first, the server responds to 100 continue, the browser sends data, and the server responds to 200 OK (return data).

20. What are the underlying Ajax implementations and readyState

  1. How to realize tab communication
  2. OSI seven layer model
  3. Reverse proxy, you know, nginx
  4. Have you ever learned about CDN
  5. How to realize tab communication

frame

  1. Vue responsive principle
  2. Vuex principle
  3. Communication mode and principle between components
  4. Do you understand MVC and MVVM? What’s the difference?
  5. How does Vue detect array changes

6. What is the role of key?

Key is mainly used to update the virtual DOM efficiently。 In addition, the key attribute will also be used in the transition switching using the same tag name element in Vue, so that Vue can distinguish it.
Reference articles

  1. Principle of JSX
  2. Virtual Dom and diff algorithm
  3. What function does the scaffold do?
  4. Vue router principle
  5. The difference between V-IF and v-show in Vue
  6. React lifecycle
  7. Compared with class, what is not easy to implement in react hook?
  8. How to optimize react?
  9. Let’s talk about high-level component hoc
  10. Talk about component design, domain model
  11. Redux principle
  12. Setstate update mechanism
  13. Fiber architecture
  14. React hook principle
  15. Differences between native events and react events
  16. High order components (HOC), mixin, hook contrast and usefulness
  17. Webpack packaging process
  18. How does webpack handle images and CSS files?
  19. What optimization has webpack done?
  20. Webpack hot update principle
  21. Underlying tapable principle of webpack

28. How does webpack implement asynchronous loading?

It is to separate some JS modules into JS files, and then create a script object and add it to the document.head object when needed. The browser will automatically initiate a request for the JS file, and then write a callback function to let the requested JS file do some business operations.

  1. Babel principle
  2. What does transform runtime do?

31. Functions and differences between Babel runtime and Babel Polyfill

Babel only converts the new JavaScript syntax by default, not the new API. For example, global objects such as iterator, generator, set, maps, proxy, reflect, symbol, promise, and some methods defined on global objects (such as object. Assign) will not be translated. If you want to use these new objects and methods, you need to provide a Polyfill for the current environment

babel-polyfill

At present, the most commonly used Polyfill used with Babel is Babel Polyfill, which will “load the whole Polyfill library”, process the new API in the compiled code, and insert some help functions into the code.

babel-runtime

Babel Polyfill solves the problem that Babel does not convert new APIs, but inserting help functions directly into the code will pollute the global environment, and different code files contain duplicate code, resulting in a larger volume of compiled code.
In order to solve this problem, Babel provides a separate package Babel runtime to provide tool functions for compiling modules. After the plug-in Babel plugin transform runtime is enabled, Babel will use the tool functions under Babel runtime. The gasket is also plug and play. This can avoid polluting the global namespace when introducing Polyfill.

Although Babel Polyfill has various disadvantages compared with Babel runtime, it cannot be replaced by Babel runtime in some cases. For example, code: [1, 2, 3]. Includes (3), object. Assign ({}, {key: ‘value’}), array, object and other ES6 methods under “instance”, Babel runtime cannot support it because Babel runtime only supports static methods.

  1. How does Babel parse strings into ast?
  2. Let’s talk about ast syntax tree
  3. Comparison between webpack and gulp
  4. Node event loop
  5. Disaster recovery in node architecture

37. Node is multi-threaded, highly concurrent and safe

Since node is a single process and cannot make full use of the performance of multi-core CPU, cluster module is generally used for multi-process deployment. In the multi process environment, it will bring some concurrency problems. The data between processes is not shared, but there will still be many shared resources, such as file system, database, etc. Concurrent access and modification of these resources can still cause problems.
Therefore, in the cluster mode, a more reliable locking mechanism is needed to ensure that only one asynchronous function can be executed for multiple node instances at a time. In order to achieve this, it is not feasible to only rely on single threaded node, and external state management needs to be introduced. The redislock algorithm provides an implementation of redis based distributed locks. For a detailed introduction of distributed lock and redlock algorithm, please refer to this linkhttps://redis.io/topics/distlock

38. Talk about stream

39. PM2 principle

40. Talk about the method of checking memory leakage

There are usually two kinds of memory leaks, one is easy to reproduce, and the other is not easy to reproduce.
For those that are easy to reproduce, we can simulate troubleshooting in the test environment.
For those that are not easy to reproduce, we need to use the memory snapshot. You can use devtool to view the memory snapshot and heapdump to save the memory snapshot. The memory snapshot saved by heapdump only contains objects in the node environment. If node inspector is used, the snapshot will contain front-end variables, which is easy to cause interference.

41. Have you read the egg source code

42. What is the difference between applet and H5? [applet underlying implementation]

43. Tell me about the underlying principle of taro applet and the difference between it and mpvue [ast, Babel

44. How does the spa project monitor PV and UV values

45. Talk about Axios. What are its advantages compared with fetch and Ajax

46. Why can Axios send requests in both the browser and the node layer?

47. Difference between client-side rendering and server-side rendering

monitor

  1. How to handle exceptions in projects
  2. Error how to capture?

3. How does the spa project monitor PV and UV values?

Use the hook of the navigation guard to report data

4. How to send statistical data to the server when the user refreshes, jumps and closes the browser?

Listen to onload or beforeunload, or define an image link as an upload interface. In addition, you can also usenavigator.sendBeacon(url, data);
sendBeaconThe method has the following characteristics:

  1. An asynchronous request is issued, andPOSTWhen the back-end parses parameters, it is necessary to pay attention to the processing method;
  2. The request sent is executed in the browser task queue, which is separated from the current page, so it will not block the unloading process of the current page and the loading process of subsequent pages, and the user experience is good;
  3. You can only judge whether it is put into the browser task queue, but not whether it is sent successfully;
  4. Beacon APIThe corresponding callback is not provided, so the back-end return is best omittedresponse body

5. Problems encountered in error log reporting

6. Load balancing mode and fault tolerance mechanism

7. How to calculate the residence time on a page

Mobile terminal

1. How can the mobile terminal optimize the white screen of the home page for too long?

2. How to optimize the mobile terminal? How is offline package implemented?

3. How many webviews are there?

Ios8 used to beUIWebview, ios8 followed byWebkitWebview

4. What are the interaction modes between WebView and native?

JavaScript notification native

  • API injection, native mounts data or methods directly in the JS context

    • Low latency, security problems and high risk below Android 4.1
  • WebView URL SchemeJump interception

    • Good compatibility, but high delay and length limit
  • In WebViewPrompt / console / Alert interception(usually prompt is used)

Native notification JavaScript:

  • IOS: stringByEvaluatingJavaScriptFromString
  • Android: loadUrl (4.4-)
  • Android: evaluateJavascript (4.4+)

5. How to troubleshoot errors in interaction?

  1. Chrome real machine debugging
  2. Weinre debugging
  3. Spy debugger debugging
  4. vconsole.js
  5. App internal commissioning interface

6. What are the browser cores and which are used by the mobile terminal?

7. Mobile page adaptation solution

rem,viewport

security

1. Do you know about front-end security? How do XSS and CSRF attack and defend?

2. SQL injection, you know?

3. Reptiles and anti reptiles

other

1. How to generate file fingerprints?

2. What is NPX?

NPX is a tool for executing node packages. It has been bundled with NPM since npm5.2.
The main problem NPX wants to solve is to call the modules installed inside the project.

  • When in executionnpx <command>What will NPX do when it is?

    • Help you find this command locally (either in the project or locally)

      • Found: just use the local version
      • Not found: download the latest version directly and complete the command requirements
    • After use, nothing will be left on your computer or project

Therefore, summary of advantages:

  • It will not pollute the machine
  • Always use the latest version of dependency

3. What are the functions of package.json?

The package.json file describes all relevant information of an NPM package, including author, introduction, package dependency, construction, etc. The format must be a strict JSON format.
Package.json file specifies the version of the project, dependent files, runnable scripts, entry files, etc

4. Have you ever used webgl?

5. The difference between SVG and canvas

6. What does git push – u mean

7. Explain the difference between git merge and git rebase

8. Can you write a binary tree and how to traverse it

9. Do you know what pseudo classes are?

10. What is the difference between XHTML and HTML?

11. How does the two-dimensional code work? Scan the two-dimensional code on the PC, and how can the PC log in?

12. How to build a real-time chat system

13. How to ensure the correct order of messages when messages are delayed?

14. Basic writing of MySQL

15. What does MySQL reference

16. Differences between MySQL and NoSQL

17. Meta tag

18. Do you know the box model?

There are two kinds of box models: 1. W3C standard box model (standard box model) 2. Ie standard box model (weird box model)
Size of box under standard box model=content(width)+ padding + border + margin
The size of the box under the weird box model=content(width+ padding + border) + margin
box-sizingYou can change the box model,border-boxIt will be calculated analytically

19. Differences between EM, REM and PX

20. Brief description of animation

21. The maintained public components need to release major updates. What should I do?

22. Talk about microservice serverless?

23. Micro front end understand?

24. Have you understood the visual form?

25. Do you know typescript?

26. What compatibility have you dealt with at ordinary times?