preface

It’s the end of the year, and it’s a good time to jump ship. Many front-end partners told me that so-and-so company was too much deducted, they worked overtime every day, and didn’t give overtime pay. There was a boy who asked for a raise, and the leader agreed verbally. Thinking that his efforts in the past few months were really not worth it, the guy directly sent a mass email and left, changing to another company and directly doubled his salary. Here I have sorted out some common interview questions, hoping to help some people who want to change jobs and pay more.

Your encouragement is my biggest support, please remember to like three times oh, thank you very much!


Network based

From entering a URL address to the browser to complete the rendering process

Some time ago, WHEN I was asked this question in an interview, I felt I didn’t answer it very well

  1. Domain name resolution (this describes the process of domain name resolution), resolve the corresponding IP address
  2. After the resolution succeeds, the TCP three-way handshake is initiated to establish a connection
  3. An HTTPS request is sent after the connection is established
  4. The server responds to the HTTPS request, and the browser gets the HTML code
  5. Browsers parse HTML code and request static resources (HTML/CSS/JS, etc.)
  6. The browser then renders it and shows it to the user

But at that time, the interviewer asked me what I did when I initiated the HTTP request to the server and then returned it to the client. However, I was confused and did not remember it. At that time, I felt very general when ANSWERING this part. Today’s summary of a complete HTTP request process goes through what

Attention! This question can be used as a starting point for a variety of topics, from HTTP web knowledge to browser principles to front-end performance optimization

Meaning of the HTTP status code

  • HTTP status code 204 (no content) The server successfully processed the request, but did not return anything
  • The page requested by HTTP status code 301 (permanent move) has been permanently moved to a new location. When the server returns this response (a response to a GET or HEAD request), it automatically forwards the requester to the new location.
  • HTTP Status Code 302 (Temporary mobile) The server is currently responding to requests from web pages in different locations, but the requester should continue to use the original location for future requests.
  • HTTP Status code 304 (unmodified) The requested page has not been modified since the last request. When the server returns this response, the web page content is not returned.
  • HTTP status code 400 (error request) The server does not understand the syntax of the request (usually parameter error).
  • HTTP status code 401 (unauthorized) requests require authentication. The server may return this response for a web page that requires login.
  • HTTP status code 403 (Forbidden) The server rejects the request. (Generally, the user permission of the client is insufficient.)
  • HTTP status code 404 (Not found) The server could not find the requested web page.

What does HTTP2.0 do to improve 3.0

Http2.0 features are as follows

  • Binary frame transmission
  • multiplexing
  • The head of compression
  • Server push

Http3.0 is a complete change from Http2.0!

HTTP is an application-layer protocol built on top of the transport layer. We all know that TCP is not the only protocol at the transport layer, but there is another powerful protocol, UDP. Both 2.0 and 1.0 are based on TCP, so they both have the same vulnerabilities and limitations as TCP. Http3.0 is built on top of UDP. So it’s qualitatively different from Http2.0.

Http3.0 features are as follows

  • Connect the migration
  • No queue head is blocked
  • Custom congestion control
  • Forward safety and forward error correction

Network Layer 7 Protocol (OSI Model)

OSI is a well-defined set of protocol specifications and has many optional parts that accomplish similar tasks. It defines the hierarchy of an open system, the interrelationships between the layers, and the possible tasks included in each layer as a framework to coordinate and organize the services provided by each layer.

The OSI reference model does not provide an approach that can be implemented, but rather describes concepts that can be used to coordinate the development of standards for interprocess communication. That is, the OSI reference model is not a standard, but rather a conceptual framework for developing standards.

  • Layer 7 application layer

The Application Layer provides an interface designed for an Application to set up communication with another Application. For example, HTTP, HTTPS, FTP, Telnet, SSH, SMTP, and POP3.

  • The sixth layer represents the layer

The Presentation Layer converts the data into a format that is compatible with the receiver’s system format and suitable for transmission.

  • Layer 5 The session layer

The Session Layer is responsible for setting up and maintaining communication connections between two computers in the computer network during data transfer.

  • Layer 4 Transport layer

The Transport Layer adds the Transport header (TH) to the data to form packets. The transport header contains the protocol used to send information. For example, transmission control Protocol (TCP).

  • Layer 3 Network layer

The Network Layer determines the path selection and forwarding of data, and adds Network table headers (NH) to packets to form packets. The network table header contains network data. For example, Internet Protocol (IP).

  • Layer 2 Data link layer

The Data Link Layer is responsible for network addressing, error detection, and error correction. When the header and tail of a table are added to a packet, a Data Frame is formed. Data link headers (DLH) are methods that contain physical addresses and error detection and correction. A data linked list tail (DLT) is a string indicating the end of a packet. For example, Ethernet, wireless local area network (Wi-Fi) and general packet radio service (GPRS).

It is divided into two sub-layers: logical Link Control (LLC) sub-layer and Media Access Control (MAC) sub-layer.

  • Layer 1 physical layer

The Physical Layer sends Data frames on a LOCAL area network (LAN). It manages the communication between computer communication devices and network media. It includes pins, voltages, cable specifications, hubs, Repeaters, network cards, host interface cards, and so on.

TCP three-way handshake

  • Client passSYNThe message segment sends a connection request to determine whether the server is enabled for port preparation. State set toSYN_SEND;
  • The server will return one if it has an open port and decides to accept connectionsSYN+ACKThe packet segment is sent to the client. The status is set toSYN_RECV;
  • The client received the message from the serverSYN+ACKPacket segment, sent to the serverACKThe message segment indicates acknowledgement. Both the client and server are set toESTABLISHEDState. Connection established, data transfer can begin.

Client: Can you receive my message? Server: Yes, can you receive my reply? Client: Ok, let’s get down to business.

Why three times? : Avoid historical connections and confirm that the request sent by the client is the person of this communication. Why not 4 times? Three times is enough for the fourth

TCP wave four times

  1. Why not twice?

    • In two cases, the client immediately disconnects and stops receiving. It is impossible to confirm whether the server has received the disconnection message, but the server may still have messages to send.
  2. Why not three times?

    • Three times, the server receives a disconnection message and sends an acceptance message to the client, but the client does not reply with the final confirmation of the disconnection.

http

1. HTTP request packet structure
  1. The first Line of the request-line contains: Request method, Request URI, protocol version, CRLF
  2. The first line is followed by several lines of request headers, including general-header, request-header, or entity-header, each ending with CRLF
  3. There is a CRLF separation between the request header and the message entity
  4. The following is an example of a request packet that may contain a message entity:
GET/separate Protocols/rfc2616 rfc2616 - sec5. HTTP / 1.1 HTML Host: www.w3.org Connection: keep alive - cache-control: max-age=0 Accept: text/html,application/xhtml+xml,application/xml; Q = 0.9, image/webp, * / *; Q =0.8 user-agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36 Referer: https://www.google.com.hk/ Accept-Encoding: gzip,deflate,sdch Accept-Language: zh-CN,zh; Q = 0.8, en. Q =0.6 Cookie: authorstyle=yes if-none-match: "2CC8-3e3073913b100" if-modified-since: authorstyle=yes if-none-match: "2CC8-3e3073913b100" if-modified-since: Wed, 01 Sep 2004 13:24:52 GMT Name = QIu&age =25 Copy codeCopy the code
2. HTTP response packet structure
  • The first line is the status line containing: HTTP version, status code, status description, followed by a CRLF
  • The first line is followed by several lines of response headers, including: generic headers, response headers, and solid headers
  • A CRLF blank line separates the response header from the response entity
  • Finally, an example of a possible message entity response message is as follows:
HTTP/1.1 200 OK Date: Tue, 08 Jul 2014 05:28:43 GMT Server: Apache/2 Last-modified: Wed, 01 Sep 2004 13:24:52 GMT # Last modified time for negotiation cache ETag: "40d7-3e3073913b100" # File hash for negotiation cache Accept-ranges: Bytes Content-Length: 16599 cache-Control: max-age=21600 # Maximum expiration time for a strong Cache: Tue, 08 Jul 2014 11:28:43 GMT # strong cache expiration time (the browser) P3P: policyref = "http://www.w3.org/2001/05/P3P/p3p.xml" content-type: text/html; Charset = ISO-8859-1 {"name": "qiu", "age": 25Copy the code
3. Common HTTP status codes and their meanings
  • 1XX: indicates the information status code

    • 100 Continue When a POST request is sent, the server sends an acknowledgement message after the HTTP header has been sent, and then sends specific parameter information
  • 2XX: success status code

    • 200 OK A normal message is displayed
    • 201 Created The request succeeds and the server creates a new resource
    • 202 Accepted the request has been Accepted but not yet processed
  • 3XX: redirection

    • 301 Moved Permanently The page for the Permanently Moved Permanently to the new location.
    • 302 Found Temporary redirect.
    • 303 See Other Temporary redirects and always uses GET to request new URIs.
    • The requested page has Not been Modified since the last request.
  • 4XX: Client error

    • 400 The Bad Request server cannot understand the format of the Request. The client should not attempt to use the same content to initiate a Request again.
    • 401 Unauthorized The request is not authorized.
    • 403 Forbidden Forbidden access.
    • 404 Not Found The resource how to match the URI was Not Found.
  • 5XX: Server error

    • 500 Internal Server Error Common Server errors.
    • 503 Service Unavailable The server cannot process the request temporarily (possibly due to overload or maintenance).

Http1.0, HTTP1.1, http2.0

§ http1.0 vs http1.1

  1. If the request header value is keep-alive, the client notifies the server to return the request result and Keep the Connection, which effectively reduces the TCP three-way handshake cost.
  2. Cache handling, increasing theCache-ControlEqual-cache correlation headers (see details below);
  3. Host is added to the request header. HTTP1.0 assumes that each server is bound to a unique IP address, so the URL in the request message does not pass the hostname. However, with the development of virtual hosting technology, there can be multiple virtual hosts (multi-homed Web Servers) on a physical server, and they share the same IP address. HTTP1.1 both Request and response messages should support the Host header field, and an error (400 Bad Request) will be reported if there is no Host header field in the Request message.
  4. Request header incrementrangeCan be used toBreakpoint continuingly, which supports requesting only a portion of a resource that is available forBreakpoint continuingly.
  5. Add request methods :(OPTIONS,PUT, DELETE, TRACE, CONNECT)
  6. 24 status codes are added, (for example, 100Continue, used before sending the request bodyRequest headerTest the server before deciding whether to send itRequest body)

Http1. X vs http2.0

  1. Server push
  2. Multiplexing, where multiple requests are made over the same TCP connection
  3. Packet header compression, HTTP2.0 can maintain a dictionary, differential update HTTP headers, greatly reduce the traffic generated by header transmission

https

HTTPS = HTTP + encryption + Authentication + Integrity protection

Shortcomings of HTTP:

  • Communication uses unencrypted plain text, and the content is easy to be stolen
  • Do not verify the identity of the communication party, vulnerable to camouflage
  • Packet integrity cannot be verified and is easily tampered

HTTPS was born to solve the security problems of HTTP protocol. HTTPS is not a new protocol at the application layer. It is based on HTTP. The HTTP and TCP interfaces are replaced by SSL and TLS.

HTTP: IP ➜ TCP ➜ HTTP (Application layer)

HTTPS: IP ➜ TCP ➜ SSL ➜ HTTP (application layer)

§ encryption

  • SSL (Secure Sockets Layer)
  • TLS (Transport Layer Security)

Symmetric encryption: Encrypt and decrypt with the same key. Common symmetric encryption algorithms: AES, RC4, 3DES Asymmetric encryption: Data encrypted with one key can be decrypted only with another key. Commonly used asymmetric encryption algorithms: RSA, DSA/DSS

Common HASH algorithms include MD5, SHA1, and SHA256

The asymmetric encryption algorithm is used to encrypt the generated password during the handshake, the symmetric encryption algorithm is used to encrypt the transmitted data, and the HASH algorithm is used to verify data integrity.

Because the browser-generated password is the key to data encryption, asymmetric encryption algorithms are used to encrypt it during transmission.

Asymmetric encryption algorithms generate public and private keys. The public key can only be used to encrypt data, so it can be transmitted at will, while the private key of a website is used to decrypt data, so websites are very careful to keep their private key to prevent leakage.

§ Information contained in CA certificate:

CA (Certification Authority)

  • The public key
  • Web site address
  • Certificate issuing authority
  • Expiration time

§ Process of HTTPS encrypted communication:

  1. The browser enters a URL and requests a web site, along with its own set of encryption rules that it supports.

  2. Website production certificate, this should be the site when the site has been done. Certificates are divided into server certificates and client certificates. When we talk about certificates, we generally refer to server certificates (

    Description of SSL certificates

    ). The production process is as follows:

    1. Make a CSR document. To create a Certificate Secure Request file, the system generates two keys. One is the public key, which is the CSR file, and the other is the private key, which is stored on the server.
    2. The CA certificate. There are two authentication methods for submitting CSR files to CA: domain name authentication and enterprise document authentication.
    3. Certificate installation. After receiving the CA certificate, deploy the certificate on the server.
  3. The website selects a set of supported encryption algorithms and hash algorithms from the encryption rules sent by the browser, and sends the certificate with the public key to the browser. The certificate also contains a lot of information, such as the website address, certificate issuing authority, and expiration time.

  4. The browser parses the certificate.

    1. Verify the validity of the certificate. For example, whether the certification authority is valid and the website address in the certificate is the same as the accessed address. If the certificate is not valid, the browser displays a message indicating that the certificate is not trusted. If the certificate is valid, the browser displays a small lock.
    2. If it is valid, or if the user accepts an invalid certificate, the browser generates a password (or key) of a random number and encrypts it with the public key provided in the certificate.
    3. The handshake message is calculated using the agreed hash and encrypted using the generated random number (i.e. the key). Finally, all the previously generated messages are sent to the website server.
  5. The web server parses the message. Use the existing private key to decrypt the key, then use the key to decrypt the handshake message, and verify that it is the same as the one sent by the browser. It then encrypts a handshake message with the key and sends it to the browser.

  6. The browser decrypts and computes the HASH of the handshake message. If the HASH is the same as that sent by the server, the handshake is complete. All subsequent communication data is encrypted using the random password generated by the previous browser using the symmetric encryption algorithm. Here, the browser and the website send encrypted handshake messages to each other and verify, in order to ensure that both sides have obtained the same password, and can encrypt and decrypt data normally, for the subsequent real data transmission test.

The following figure shows the process of HTTPS encrypted communication:

JS

What is event broker (event delegate) and what are the benefits

The idea behind event delegation is that instead of setting event listeners on each child node, you set event listeners on its parent node and then set each child node using the bubbling principle.

Advantages:

  • In JavaScript, the number of event handlers added to the page is directly related to the overall performance of the page, because the more dom manipulation is required, the more likely it is to cause browser redraw and reflow, and the longer the page interaction events become. That’s why you want to reduce dom manipulation. Each event handler is an object, and each additional event handler takes up more space in memory. If you want to use the event delegate, you will put all the operations into the JS program, only to its parent level operation, and dom operation only need to interact once, so that can greatly reduce the number of interactions with DOM, improve performance;
  • Dynamically bound events because the event is bound to the parent element, new elements can fire the same event

The addEventListener defaults to capture or bubble

The default is bubbling

The third argument to addEventListener defaults to false to perform event bubbling.

When true, the event capture behavior is performed.

Apply, call, bind

  • All three can change the function’s this object.
  • The first argument in all three cases is the object to which this refers. If there is no argument or the argument is undefined or null, it points to the global window by default.
  • All three can be passed, but apply is an array, call is a list of parameters, and apply and call are passed once, while bind can be passed multiple times.
  • Bind is a function that returns after binding this for later call; Apply and call are executed immediately.
  • Bind () returns a new function, and if the new function is used as a constructor to create a new object, this no longer points to the first argument passed to Bind, but to the instance created with new

Attention! Many students may overlook the fact that the bind function is used as a constructor for new instantiation

Give examples of closures in real life

For example, the common anti-shake throttling

Function debounce(fn, delay = 300) {let timer; Return function () {const args = arguments; if (timer) { clearTimeout(timer); } timer = setTimeout(() => { fn.apply(this, args); }, delay); }; } Duplicate codeCopy the code

Block-level scopes can be simulated in JavaScript using closures

function outputNumbers(count) { (function () { for (var i = 0; i < count; i++) { alert(i); }}) (); alert(i); // Cause an error! } Duplicate codeCopy the code

Closures can be used to create private variables in objects

var aaa = (function () { var a = 1; function bbb() { a++; console.log(a); } function ccc() { a++; console.log(a); } return {b: BBB, //json structure c: CCC,}; }) (); console.log(aaa.a); //undefined aaa.b(); //2 aaa.c(); / / 3Copy the code

Event loop topics (Code output order)

setTimeout(function () { console.log("1"); }, 0); async function async1() { console.log("2"); const data = await async2(); console.log("3"); return data; } async function async2() { return new Promise((resolve) => { console.log("4"); Resolve ("async2 result "); }).then((data) => { console.log("5"); return data; }); } async1().then((data) => { console.log("6"); console.log(data); }); new Promise(function (resolve) { console.log("7"); // resolve() }).then(function () { console.log("8"); }); Copy the codeCopy the code

Result: 247536 Async2 result 1

Attention! I buried a pit in the last Promise, and I didn’t call the resolve method. I met this pit in the interview of Meituan. At that time, I didn’t see it clearly and thought it was the same routine

Write a bind

/ / bind implementation is a little complex Because he considered the situation more Also involves the parameter (similar Function curry) Function. The prototype. MyBind = Function (context,... args) { if (! context || context === null) { context = window; } // create a unique key for the internal method name of the context we construct. context[fn] = this; let _this = this; // bind const result = function (... InnerArgs) {// If we use the new operator as a constructor, we do not bind this. The new operator calls this to the result instance, which in turn inherits from _this.__proto__ === result.prototype //this instanceof result =>true // this.__proto__.__proto__ === result.prototype.__proto__ === _this.prototype; //this instanceof _this =>true if (this instanceof _this === = true) {if (this instanceof _this === true) _this; this[fn](... [...args, ...innerArgs]); Bind: delete this[fn]; } else {// If it is called as a normal function then it is very simple to change this to refer to the passed context context[fn](... [...args, ...innerArgs]); delete context[fn]; }}; Create result.prototype = object.create (this.prototype); return result; }; // function Person(name, age) {// console.log(name); // console.log(age); // console.log(this); // constructor this points to the instance object //} // // constructor prototype method // person.prototype. say = function() {// console.log(123); // let obj = {// objName: 'I am the name of obj ', // objAge: // function normalFun(name, age) {// console.log(name); // console.log(age); // console.log(this); // The normal function this points to the first argument to bind, which in our example is obj // console.log(this.objname); // console.log(this.objage); // console.log(this.objage); // let bindFun = person.mybind (obj, 'I am the name of the parameter passed in ') // let a = new bindFun(' I am the age of the parameter passed in ') // a.say() //123 // test again as a normal function call // let bindFun = Normalfun. myBind(obj, 'I am the name of the parameter passed in ') // bindFun(' I am the age of the parameter passed in ') copies the codeCopy the code

Handwritten promise.all and race

Static all(promiseArr) {let result = []; // declare a count for each promise return with let count = 0; return new Mypromise((resolve, reject) => { for (let i = 0; i < promiseArr.length; Promise.resolve(promiseArr[I]). Then ((res) => {// We can't push the array directly Result [I] = res; count++; If (count === promise.length) {resolve(result); } }, (err) => { reject(err); }); }}); } static race(promiseArr) {return new Mypromise((resolve, reject) => {for (let I = 0; i < promiseArr.length; I ++) {promise.resolve (promiseArr[I]). Then ((res) => {// Resolve (res); }, (err) => { reject(err); }); }}); }} Copy the codeCopy the code

Handwriting – Implements a parasitic combination inheritance

function Parent(name) { this.name = name; this.say = () => { console.log(111); }; } Parent.prototype.play = () => { console.log(222); }; function Children(name) { Parent.call(this); this.name = name; } Children.prototype = Object.create(Parent.prototype); Children.prototype.constructor = Children; // let child = new Children("111"); // // console.log(child.name); // // child.say(); // // child.play(); Copy the codeCopy the code

Handwritten -new operator

function myNew(fn, ... args) { let obj = Object.create(fn.prototype); let res = fn.call(obj, ... args); if (res && (typeof res === "object" || typeof res === "function")) { return res; } return obj; // // function Person(name, age) {// // this.name = name; // // this.age = age; // // } // // Person.prototype.say = function() { // // console.log(this.age); / / / /}; // // let p1 = myNew(Person, "lihua", 18); // // console.log(p1.name); // // console.log(p1); // // p1.say(); Copy the codeCopy the code

Hand-settimeout Simulates the implementation of setInterval

function mySetInterval(fn, time = 1000) { let timer = null, isClear = false; function interval() { if (isClear) { isClear = false; clearTimeout(timer); return; } fn(); timer = setTimeout(interval, time); } timer = setTimeout(interval, time); return () => { isClear = true; }; } Duplicate codeCopy the code

Write – publish – subscribe model

class EventEmitter { constructor() { this.events = {}; } // Implement subscription on(type, callBack) {if (! this.events[type]) { this.events[type] = [callBack]; } else { this.events[type].push(callBack); }} // Delete subscription off(type, callBack) {if (! this.events[type]) return; this.events[type] = this.events[type].filter((item) => { return item ! == callBack; }); Function fn() {callBack(); function fn() {callBack(); this.off(type, fn); } this.on(type, fn); } // Emit the event emit(type,... rest) { this.events[type] && this.events[type].forEach((fn) => fn.apply(this, rest)); // Const event = new EventEmitter(); // const handle = (... rest) => { // console.log(rest); / /}; // event.on("click", handle); // event.emit("click", 1, 2, 3, 4); // event.off("click", handle); // event.emit("click", 1, 2); // event.once("dbClick", () => { // console.log(123456); / /}); // event.emit("dbClick"); // event.emit("dbClick"); Copy the codeCopy the code

Handwriting – anti – shake throttling

// function debounce(fn, delay = 300) { return function () { const args = arguments; if (timer) { clearTimeout(timer); } timer = setTimeout(() => { fn.apply(this, args); // Change this to refer to the object referred to by the call debounce}, delay); }; } window.addEventListener( "scroll", debounce(() => { console.log(111); }, 1000)); Function throttle(fn, delay) {let flag = true; return () => { if (! flag) return; flag = false; timer = setTimeout(() => { fn(); flag = true; }, delay); }; } window.addEventListener( "scroll", throttle(() => { console.log(111); }, 1000)); Copy the codeCopy the code

Handwriting – Converting a virtual Dom to a real Dom

{ tag: 'DIV', attrs:{ id:'app' }, children: [ { tag: 'SPAN', children: [ { tag: 'A', children: [] } ] }, { tag: 'SPAN', children: [ { tag: 'A', children: [] }, { tag: 'A', children: []}}}]] to appeal the virtual real Dom Dom into below < div id = "app" > < span > < a > < / a > < / span > < span > < a > < / a > < a > < / a > < / span > < / div > duplicate codeCopy the code

The answer

Function _render(vnode) {if (typeof vnode === "number") {vnode = String(vnode); Return document.createTextNode(vnode); if (typeof vNode === "string") {return document.createTextNode(vnode); } // const DOM = document.createElement(vnode.tag); If (vnode.attrs) {// Traversing the attribute object.keys (vnode.attrs).foreach ((key) => {const value = vnode.attrs[key]; dom.setAttribute(key, value); }); } vnode.children.foreach ((child) => dom.appendChild(_render(child))); return dom; } Duplicate codeCopy the code

Handwriting – Implements the Flatten method for an object

Topic describes

Const obj = {a: {b: 1, 2: c, d: {e: 5}}, b: [1, 3, 3} {2, a: b:], c: 3} flatten (obj) results returned the following / / {/ / 'a.' : 1, / / 'a.c: 2, / /' A.D.E: 5, / / 'b [0] : 1, / /' b [1] : 3, / / 'b [2]. A' : 2, / / ' 'b [2]. B: 3 / / c: / /} 3 duplicate codeCopy the code

The answer

function isObject(val) { return typeof val === "object" && val ! == null; } function flatten(obj) { if (! isObject(obj)) { return; } let res = {}; const dfs = (cur, prefix) => { if (isObject(cur)) { if (Array.isArray(cur)) { cur.forEach((item, index) => { dfs(item, `${prefix}[${index}]`); }); } else { for (let k in cur) { dfs(cur[k], `${prefix}${prefix ? "." : ""}${k}`); } } } else { res[prefix] = cur; }}; dfs(obj, ""); return res; } flatten(); Copy the codeCopy the code

Handwriting – Determines whether the parenthesis string is valid

Topic describes

Given a only include a '(',') ', '{','} ', '/', ' 'the string s, determine whether a string is effective. A valid string must meet the following requirements: The left parenthesis must be closed with the same type of the right parenthesis. The left parentheses must be closed in the correct order. Example 1: Input: s = "()" Output: true Example 2: Input: s = "()[]{}" Output: true Example 3: Input: s = "(]" Output: false Copy codeCopy the code

The answer

const isValid = function (s) { if (s.length % 2 === 1) { return false; } const regObj = { "{": "}", "(": ")", "[": "]", }; let stack = []; for (let i = 0; i < s.length; i++) { if (s[i] === "{" || s[i] === "(" || s[i] === "[") { stack.push(s[i]); } else { const cur = stack.pop(); If (s[I]!== regObj[cur]) {return false;}}} if (stack.length) {return false;} return true;}; duplicate codeCopy the code

Handwriting – Find array common prefixes

Topic describes

Write a function to find the longest public prefix in an array of strings. Returns the empty string "" if no public prefix exists. Example 1: Input: STRS = ["flower","flow","flight"] Output: "FL" Example 2: Input: STRS = ["dog","racecar","car"] Output: "" Description: The input does not have a public prefix. Copy the codeCopy the code

The answer

const longestCommonPrefix = function (strs) { const str = strs[0]; let index = 0; while (index < str.length) { const strCur = str.slice(0, index + 1); for (let i = 0; i < strs.length; i++) { if (! strs[i] || ! strs[i].startsWith(strCur)) { return str.slice(0, index); } } index++; } return str; }; Copy the codeCopy the code

Handwritten – The longest non-repeating substring of a string

Topic describes

Given a string s, find the length of the smallest string that does not contain repeating characters. Example 1: Input: s = "abcabcbb" Output: 3 Explanation: Since the oldest string without repeating characters is "ABC", its length is 3. Example 2: Input: s = "BBBBB" Output: 1 Explanation: Since the oldest string without repeating characters is "b", its length is 1. Example 3: Input: s = "pwwkew" Output: 3 Explanation: Since the oldest string without repeating characters is "wKE", its length is 3. Note that your answer must be the length of the substring, "pwke" is a subsequence, not a substring. Example 4: Input: s = "" Output: 0 Copy codeCopy the code

The answer

const lengthOfLongestSubstring = function (s) { if (s.length === 0) { return 0; } let left = 0; let right = 1; let max = 0; while (right <= s.length) { let lr = s.slice(left, right); const index = lr.indexOf(s[right]); if (index > -1) { left = index + left + 1; } else { lr = s.slice(left, right + 1); max = Math.max(max, lr.length); } right++; } return max; }; Copy the codeCopy the code

Handwriting – how to find the first array in the smallest positive integer does not appear how to optimize

Given an unsorted integer array nums, find the smallest positive integer that does not appear in it. You implement a solution with O(n) time complexity and use only constant level extra space. Example 1: input: nums = [1,2,0] output: 3 example 2: input: nums = [3,4,-1,1] output: 2 example 3: input: nums = [7,8,9,11,12] output: 1 copy the codeCopy the code

This is a bit of an algorithm problem that is constantly trying to optimize the idea of the algorithm

  • The first version O(n^2) method
const firstMissingPositive = (nums) => { let i = 0; let res = 1; while (i < nums.length) { if (nums[i] == res) { res++; i = 0; } else { i++; } } return res; }; Copy the codeCopy the code
  • The second edition is O(n) in time and space.
const firstMissingPositive = (nums) => { const set = new Set(); for (let i = 0; i < nums.length; i++) { set.add(nums[i]); } for (let i = 1; i <= nums.length + 1; i++) { if (! set.has(i)) { return i; }}}; Copy the codeCopy the code
  • The final version has O(n) time complexity and uses only constant level space
const firstMissingPositive = (nums) => { for (let i = 0; i < nums.length; I ++) {while (nums[I] >= 1 && nums[I] <= nums.length && // arrange nums[I] -1]! Const temp == nums[I] // const temp = nums[I] -1; Nums [I] -1] = nums[I]; nums[i] = temp; }} // now expect [1,2,3...] For (let I = 0; i < nums.length; i++) { if (nums[i] ! = i + 1) { return i + 1; } } return nums.length + 1; // find element 1~nums.length full array}; Copy the codeCopy the code

Handwriting – how many methods can be used to generate a non-repeating random number set of length N in the rendering data source

  • First version time complexity O(n^2)
function getTenNum(testArray, n) { let result = []; for (let i = 0; i < n; ++i) { const random = Math.floor(Math.random() * testArray.length); const cur = testArray[random]; if (result.includes(cur)) { i--; break; } result.push(cur); } return result; } const testArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]; const resArr = getTenNum(testArray, 10); Copy the codeCopy the code
  • Second edition tokenization/custom attribute method time complexity O(n)
function getTenNum(testArray, n) { let hash = {}; let result = []; let ranNum = n; while (ranNum > 0) { const ran = Math.floor(Math.random() * testArray.length); if (! hash[ran]) { hash[ran] = true; result.push(ran); ranNum--; } } return result; } const testArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]; const resArr = getTenNum(testArray, 10); Copy the codeCopy the code
  • The time complexity of the third edition switching method is O(n)
function getTenNum(testArray, n) { const cloneArr = [...testArray]; let result = []; for (let i = 0; i < n; i++) { debugger; const ran = Math.floor(Math.random() * (cloneArr.length - i)); result.push(cloneArr[ran]); cloneArr[ran] = cloneArr[cloneArr.length - i - 1]; } return result; } const testArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]; const resArr = getTenNum(testArray, 14); Copy the codeCopy the code

It’s worth mentioning that swapping is a common idea in algorithms when you’re dealing with arrays

  • The time complexity of traversal and deletion in the final version is O(n)
function getTenNum(testArray, n) { const cloneArr = [...testArray]; let result = []; for (let i = 0; i < n; ++i) { const random = Math.floor(Math.random() * cloneArr.length); const cur = cloneArr[random]; result.push(cur); cloneArr.splice(random, 1); } return result; } const testArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]; const resArr = getTenNum(testArray, 14); Copy the codeCopy the code

Prototype chain judgment

Please write down the answers below

Object.prototype.__proto__; Function.prototype.__proto__; Object.__proto__; Object instanceof Function; Function instanceof Object; Function.prototype === Function.__proto__; Copy code object.prototype.__proto__; //null Function.prototype.__proto__; //Object.prototype Object.__proto__; //Function.prototype Object instanceof Function; //true Function instanceof Object; //true Function.prototype === Function.__proto__; //true copies the codeCopy the code

This topic deeply investigates the knowledge points related to prototype chain, especially the relationship between Function and Object

Es6 let implementation principle

Original ES6 code

var funcs = []; for (let i = 0; i < 10; i++) { funcs[i] = function () { console.log(i); }; } funcs[0](); // 0 Copies the codeCopy the code

Es5 code compiled by Babel (Polyfill)

var funcs = []; var _loop = function _loop(i) { funcs[i] = function () { console.log(i); }; }; for (var i = 0; i < 10; i++) { _loop(i); } funcs[0](); // 0 Copies the codeCopy the code

In fact, we can see from the results of Babel compilation that let uses closures and function scope to achieve block-level scope effect. In different cases, let compilation results are different

Js regular substitution

To replace a paragraph of text that conforms to a regular rule with another paragraph related to the original text

Replace (regex,function(Element,index){})

var t="33aabb44aabb55aabbcc"; t=t.replace(/\d{2}/g,function(m,i){return "<b>"+m+"</b>"; });Copy the code

CSS

What is CSS rendering layer composition how do browsers create new rendering layers

In the DOM tree, each node corresponds to a RenderObject. When their rendering objects are in the same coordinate space (z-axis space), a RenderLayers will be formed, which is also called the rendering layer. The rendering layer ensures that the page elements are stacked in the correct order, which is when composite layers are created to properly handle the display of transparent and overlapping elements. This process is especially important for pages with overlapping elements, because if the layers are merged in the wrong order, the elements will display incorrectly.

How is the CSS priority calculated

  • First priority:! Important overrides element styles anywhere on the page
  • 1. Inline style, for example, style=”color: green”, weight: 1000
  • 2.ID selectors, such as #app, have a weight of 0100
  • 3. Class, pseudo-class, attribute selector, such as. Foo, :first-child, div[class=”foo”], weight 0010
  • 4. Tags and pseudo-element selectors, such as div::first-line, have a weight of 0001
  • 5. Wildcard, subclass selector, sibling selector, such as *, >, +, weight is 0000
  • 6. Inherited styles have no weights

What are the values and functions of position

  • static

    Static (without position) is the default value for position, and the element is in normal document flow, ignoring the left, top, right, bottom, and Z-index attributes.

  • relative

    Relative refers to the position of an element relative to its original position. Elements are not removed from the flow of the document, so the original position of the element is retained and the position of other elements is not affected.

    Usage scenario: Child element is positioned relative to parent element

  • Absolute Absolute refers to the setting of an absolute position on an element. Objects that are relatively located can be divided into two situations:

    1. Element with absolute If there is an ancestor element with position set to relative or absolute, then the element’s location object is the ancestor element with position set.
    2. If the ancestor element of the position attribute is not set, then the position is positioned relative to the body. Use scenario: Follow the icon Icon uses the absolute and margin attributes independent of the positioning parent, so that the position of the icon can be adjusted when the number of characters in the text changes
  • Fixed can simply be said to be a special version of absolute, fixed elements are always positioned relative to the body. Usage scenario: sidebar or AD graphics

  • Inherit inherits the position property of the parent element, but note that Internet Explorer 8 and previous versions do not support inherit.

  • If a sticky element is set, its position will not be affected by its location in viewport (top, left and other attributes are invalid). When the element is about to move out of the offset range, its location will be changed to fixed. Set the left and top properties to a fixed position. When an element is rolled past a specified offset value, it is fixed to the specified position within the container. That is, if you set top: 50px, the sticky element will be fixed when it reaches 50px at the top of the relative positioned element and will no longer move upwards.

    Usage scenario: Follow the window

Vertical horizontal center implementation

This is basically a CLASSIC CSS problem but there are already a lot of generic answers on the Internet if you want to score points on this problem

Many different schemes can be implemented for fixed and variable width heights

How to Enable Hardware Acceleration of the CSS (GPU Acceleration)

The browser will use GPU rendering when processing the CSS below

  • Transform (GPU acceleration is used when 3D transform styles appear)
  • opacity
  • filter
  • will-change
Use transform: translateZ(0) use transform: translate3D (0, 0, 0) using the WILL-change property of CSS. Will-change can be set to opacity, transform, top, left, bottom, and right. Copy the codeCopy the code

Attention! Layer of explosion, for some reason may lead to a large number of composite layer, not in expected despite the browser layer compression mechanism, but also has a lot of cannot be compressed, this layer of explosion phenomena may appear (simple understanding is that many don’t need to be upgraded to synthetic layer elements for some improper operation became the composite layer). To solve the problem of layer explosion, the best solution is to break the condition of overlap, that is to say, let other elements not overlap with the elements of composite layer. Simple and direct way: when using 3D hardware acceleration to improve animation performance, it is best to add a Z-index attribute to the element, artificial interference composition of the sorting, can effectively reduce the creation of unnecessary layers of composition, improve rendering performance, especially mobile optimization effect.

Flex :1 is made up of attributes

Flex is actually a contraction of flex-grow, Flex-shrink, and Flex-basis.

Flex-grow: defines the scale of the project;

The default value is 0, that is, it will not be enlarged even if there is free space. Flex-grow for all projects is 1: evenly divide the remaining space (auto zoom space placeholder); An item with flex-grow of N takes up n times as much space (magnification ratio) as an item with Flex-grow of 1. Copy the codeCopy the code

Flex-shrink: defines the shrink of a project;

The default is 1, which means that the project shrinks if there is insufficient space; The flex-shrink value is 1 for all projects: when space is insufficient, the amount of shrink is the same. If flex-shrink is 0, the project does not shrink when space is insufficient. A flex-shrink of N will shrink n times as much when space is insufficient as a Flex-shrink of 1. Copy the codeCopy the code

Flex-basis: Defines the main size of the project prior to allocating extra space. The browser uses this property to calculate whether there is extra space on the main axis

The default value is auto, the original size of the project; After setting, the project will occupy a fixed space. Copy the codeCopy the code

BFC

A BFC is a Block Formatting Context, which is a render area used to layout Block boxes.

In simple terms, a BFC is actually a region in which certain rules are followed, a unique set of rendering rules.

Document flow can be divided into three types: normal flow, location flow and floating flow. Normal flow actually refers to FC in BFC, also known as formatting context.

Normal flow: Elements are laid out from top to bottom and left to right according to their sequence in THE HTML. In this process, the inline elements are arranged horizontally until, when the row is full and the line is wrapped, the block-level elements are rendered as a complete new row.

Formatting context: a rendering area of a page with a set of rendering rules that determine how its children are laid out and how they interact with other elements

§ Several rules of BFC: 1) The margins of elements in the BFC area overlap. 2) Elements in the BFC region do not overlap with floating elements. 3) When calculating the height of the BFC area, the floating element is also involved in the calculation. 4) THE BFC region is like a container, the inside elements do not affect the outside, and the outside elements do not affect the inside.

§ Application of BFC:

  1. Clear float: Parent element sets overflow: Hidden Triggers the BFC implementation to clear float, prevent parent element height collapse, following element overwrite, implement text wrap, etc.
  2. Eliminate vertical margin overlap for adjacent elements: the second child element covers one layer and sets Overflow: Hidden, building the BFC so that it does not affect external elements.
  3. Eliminates margin overlap between parent and child elements, and sets overflow: hidden for the parent element

§ Methods of triggering BFC:

  1. Float is not None, and the region of the floating element is a BFC region.
  2. The region of an element whose position is not static or relative is a BFC region
  3. The area where the table cell element displayed as table-cell resides is also a BFC area
  4. The area where overflow elements are not visible is also a BFC area

The browser

How does the browser create a new rendering layer

  • The root document
  • Have clear positioning attributes (relative, fixed, sticky, absolute)
  • opacity < 1
  • It has the CSS fliter property
  • The CSS mask property is available
  • Has the CSS mix-blending-mode property and the value is not normal
  • Has a CSS transform property and is not None
  • Backface -visibility property is hidden
  • CSS Reflection property
  • It has the CSS column-count attribute and the value is not auto or it has the CSS column-width attribute and the value is not auto
  • Currently, animations are applied to opacity, Transform, fliter, and backdrop filter
  • The overflow is not visible

Attention! Many people will confuse these compositing layer conditions with the rendering layer conditions, which occur in two different layers and are completely different

What does 304 mean? What are the common scenarios, and what status codes are returned by hitting the strong cache

Negotiation cache hit returns 304

This approach uses two fields in the headers request header, last-modified & if-Modified-since. The server tells the browser when the resource was Last Modified via the last-modified response header:

Last-Modified: Thu, 20 Jun 2019 15:58:05 GMT

When the resource is requested again, the browser needs to confirm to the server that the resource is expired. This proof is the if-Modified-since field in the request header, which is the value of the last-Modified field in the response header in the previous request:

If-Modified-Since: Thu, 20 Jun 2019 15:58:05 GMT

The server checks if-modified-since in the request header when the browser sends a request, and returns 304 If the last modified time is the same. Otherwise, last-Modified is added to the response header and the response body is returned.

In addition, when the browser sends a request, the server checks the if-none-match value in the request header against the contents of the current file using a hash algorithm (such as nodejs) : Cryto.createhash (‘sha1’)) returns 304; otherwise, add the etag attribute to the current response header and return the content.

To sum up, it can be summarized as follows:

The last-Modified date of the request header matches the last-Modified date of the response header. The hash of the request header if-none-match matches the etag of the response header. Both cases return the Status Code: 304 copy CodeCopy the code

Strong cache hit 200 200

What are RAF and RIC

RequestAnimationFrame: tells the browser to execute the incoming callback function (usually manipulating the DOM, updating the animation) before the next redraw Since it is executed once per frame, this results in the same number of executions per second as the number of browser screen refreshes, usually 60 per second.

RequestIdleCallback: : performs callbacks during browser idle time, which allows developers to perform low-priority tasks in the main event loop without affecting some later-critical events. If there are multiple callbacks, they are executed on a first-in, first-out basis, but when timeout is passed, it is possible to shuffle the order to avoid timeouts.

Cache-Control

It is used to determine strong cache, that is, whether to fetch the cached file directly from the client without requesting the backend.

Both request headers and response headers can be used.

The cache commands in the request include no-cache, no-store, max-age, max-stale, min-fresh, and only-if-cached. The commands in the response message include: Public, private, no-cache, no-store, no-transform, must-revalidate, proxy-revalidate, max-age.

The meanings of common commands are as follows:

  • no-cache: Do not use local cache. Cache negotiation is required to verify with the server whether the returned response has been changed. If there is an ETag in the previous response, the request will be verified with the server. If the resource has not been changed, the re-download can be avoided.
  • no-store: Directly forbids the browser to cache data, each time the user requests the resource, a request will be sent to the server, each time the complete resource will be downloaded.
  • public: can be cached by all users, including end users and intermediate proxy servers such as CDN.
  • private: can be cached only by the browser of the end user and cannot be cached by a trunk cache server such as the CDN.
  • max-age: indicates that the client can receive a response with a lifetime not longer than the specified time in seconds.

packaging

webpack

  • webpackWebpack is a module packaging tool, you can use Webpack to manage yourModule is dependent onAnd,Compilation of outputStatic files required by the modules.
  • It can well manage and package HTML, Javascript, CSS and various static files (images, fonts, etc.) used in Web development, making the development process more efficient.
  • Webpack has module loaders for different types of resourcesloader.
  • The WebPack module packer analyzes the dependencies between modules to generate optimized and merged static resources.
  • Its plug-in functionality provides various lifecycle hooks in the process of processing various files, enabling developers to use the plug-in functionality to develop many custom functions.

Differences between webPack Plugin and Loader

  • Loader:

    For converting module source code, Loader describes how WebPack handles non-javascript modules and introduces these dependencies into BULD. Loader can convert files from different languages (such as TypeScript) to JavaScript, or convert inline images to data urls. For example, CSS-loader, style-loader and so on.

  • Plugin

    Designed to address other things loader can’t do, it works directly on WebPack and extends its functionality. A number of events are broadcast during the life cycle of a WebPack run, and the Plugin can listen for these events and change the output when appropriate through the API provided by WebPack. Plug-ins range from packaging optimization and compression to redefining variables in the environment. Plug-in interfaces are extremely powerful and can be used to handle a wide variety of tasks.

The Tree Shaking shook the Tree

When we write several methods but only use one, we need to remove code when we package. That’s what Tree shaking is for. Tree shaking only supports ES Module syntax like import and export. It doesn’t support commonJS syntax like require.

Background: In the project, there is an entry file, which is equivalent to the trunk of a tree, and an entry file has many dependent modules, which are equivalent to branches. In reality, you rely on a module but only use some of its functionality. Tree-shaking is a way to remove useless code by shaking off unused modules.

Static analysis of code based on the module system provided by ES6, and remove dead code from the code. Therefore, Tree Shaking technology makes it easy to optimize our code and reduce the size of our code.

Tree Shaking is borrowed from the rollup implementation.

Webpack statically analyzes the dependency tree of the code based on the module system provided by ES6, and marks import & Export as 3 classes:

  • All imports are marked as /* harmony import */
  • / Harmony export([type])/, where [type] is binding, immutable, etc.
  • The unused export is marked as /* unused Harmony export [FuncName] */, where [FuncName] is the name of the export method, and then Uglifyjs (or some similar tool) is used to simplify the code and delete the unused ones.

Why based on ES6 module implementation (ES6 Module features:) :

  • Can only appear as a statement at the top level of a module
  • The module name for import must be a string constant
  • Import binding is immutable

Condition:

  1. First source code must follow ES6 module specification (import & export), if it is CommonJS specification (require) can not be used.
  2. Module code cannot be written with side effects and will not be removed if external variables are changed inside the code.

Configuration method:

  1. Add a property to package.json:
{// sideEffects if set to false, Webpack considers all unused functions to be harmless, i.e. deleted. "SideEffects ": false, // Set blacklist to prevent error deletion of code "sideEffects": // SRC /some-side-effectful-file.js],} [// SRC /some-side-effectful-file.js]Copy the code

Tree -shaking off unused code is automatically enabled in production mode

Tree-shaking is not a configuration option in Webpack, it is an optimization of a set of features that are used together and start automatically in production mode

// In development mode, usedExports: true will only indicate which modules are not in use, not delete them, because it may affect the accuracy of source-map marker locations. {mode: 'develpoment', optimization: {// To optimize the exported module usedExports: true},} {mode: 'production', // {// Export only module members for external use responsible for labeling dead leaves usedExports: true, minimize: ** * WebPack packs modules into a single closure by default ** The new API in WebPack 3 puts all modules in a single function to merge them together as much as possible * to improve efficiency, */ concatenateModules: true,},}Copy the code

Tips for using tree shakers:

  1. Write code using ES6 module syntax
  2. Utility class functions should be output as separate functions, not as a single object or class
  3. The statement sideEffects
  4. Be aware of side effects when refactoring code yourself

Tree shaking & Babel Using babel-loader to process JS code will cause tree shaking to fail.

  • The premise for treeshaking must be code organized by ES Module, that is, the code assigned to the ESMOdule must be ESM. It is possible to convert ESM to commonJS specification after using babel-loader to process JS code (PRESET -env plugin will set ESM => coommonjs)

Solution: Receive modules: false configured for preset-env and make sure automatic conversion is not turned on (conversion to commonJS is automatically turned off for us in the latest version of babel-Loader)

presets: [
    ['@babel/preset-env', {"modules": false}]
]
Copy the code

Introduction to Common plug-ins

  • webpack-dev-server
  • Clean-webpack-plugin: Clean up the output directory before compilation
  • CopyWebpackPlugin: Copies the file
  • HotModuleReplacementPlugin: hot update
  • ProvidePlugin: Global variable Settings
  • DefinePlugin: Define global constants
  • SplitChunks (old versions use CommonsChunkPlugin) : Extract common modules and bundle together modules that match the number of references
  • Mini-css-extract-plugin (old version used ExtractTextWebpackPlugin) : CSS is packaged separately
  • TerserPlugin (older version uses UglifyJsPlugin) : Zip code
  • Progress-bar-webpack-plugin: Compels the progress bar
  • DllPlugin& DllReferencePlugin: Improve packaging efficiency and only package third party modules once
  • Webpack-bundle-analyzer: Visually looks at the size of each file packed by webpack
  • Thread-loader,happypack: Multi-process compilation to speed up compilation

How the plug-in is implemented

Tabable (Sync + Async)Hooks === Compiler + Compiletion

The Compiler object represents the complete Configuration of the WebPack environment. This object is created once when webPack is started, and all the actionable Settings are configured, including Options, Loader, and plugin. When a plug-in is applied in a WebPack environment, the plug-in receives a reference to this Compiler object. You can use it to access the main webPack environment

The compilation object represents a resource version build. When running the WebPack development environment middleware, each time a file change is detected, a new compilation is created, resulting in a new compilation resource. A compilation object represents the current module resources, compile-generated resources, changing files, and information about the state of the dependencies being tracked. The Compilation object also provides a number of critical timing callbacks that plug-ins can choose to use when doing custom processing

Create a plug-in function that defines the Apply method on its Prototype and specifies a WebPack event hook

The function handles the specific data of the webPack instance internally

When the processing is complete, call the callback function provided by WebPack

The function MyWebpackPlugin () (}; . / / the prototype is defined on the apply method MyWebpackPlugin prototype. Apply = function () {/ / specified function to an event to webpack mount Compiler. PluginCwebpacksEventHook funcion "(compiler) (the console. The log (" this is a plug-in"); // Webpack callback()})Copy the code

What is Tree shaking, and how does it work

Tree shaking is a technique for optimizing the packaging volume of a project by removing redundant code, known as Dead Code Elimination

What does Tree shaking work for?

ES6 Module is introduced for static analysis, so when compiling, it is correct to determine which Module static analysis program flow is loaded, determine which modules and variables are not used or referenced, and then delete the corresponding code copy codeCopy the code

Extensions: What are the differences between common.js and es6 module introductions?

CommonJS is a module specification that was originally applied to Nodejs as the module specification for Nodejs. JavaScript running on the browser side also lacks a similar specification, so before ES6 came out, the same module specification was implemented on the front end (e.g. AMD) to manage the front end modules. Since ES6, a new ES6 Module specification has been introduced, which implements Module functions at the level of language standards and is quite simple to implement. It is expected to become a common Module solution for browsers and servers. However, ES6 Module is not compatible with browsers at present. Export and import that we usually use in Webpack will be converted to CommonJS by Babel. The main differences in use are:

CommonJS module outputs a copy of a value, ES6 module outputs a reference to a value.

2, CommonJS module is run time load, ES6 module is compile time output interface (statically compiled).

3, CommonJs is a single value export, ES6 Module can export multiple

ES6 Module static syntax can only be written at the top level

5, CommonJs this is the current Module, ES6 Module this is undefined

What is Babel? Do you know how it works

Babel is a JavaScript compiler. It compiles the latest version of javascript into a currently executable version. In short, Babel allows us to freely use the new es6 and even ES7 syntax in our current projects.

The three main processing steps of Babel are: parse, transform and generate.

  • Parsing parses code into abstract syntax trees (AST). Each JS engine (such as V8 in Chrome) has its own AST parser, and Babel is implemented through Babylon. In the parsing process, there are two stages: lexical analysis and syntax analysis. The lexical analysis stage transforms strings of code into a stream of tokens. Tokens are like nodes in the AST. The parsing phase converts a token flow into the AST form and converts the information in the token into the AST representation structure.
  • At this stage, Babel receives the AST and performs depth-first traversal with babel-traverse, adding, updating, and removing nodes. This is where the Babel plug-in comes in.
  • Generating transforms the transformed AST into JS code via babel-Generator by going depth-first through the AST and building a string that represents the transformed code.

Vue

Vue component communication methods

  • The props and EMIT parent components pass data to the child components via prop, the child components pass data to the parent components via PROP, the child components pass data to the parent components via prop, and the emit parent components pass data to the child components via prop, The child component passes data to the parent component by emitting an event
  • The parent, the parent, the parent and children takes the current components of the parent component and the current component child components
  • Attrs and listeners A->B->C Vue 2.4 starts with attrs and attrs and attrs and Listeners to address this problem
  • Variables are provided by provide in the parent component and injected by inject in the child component. (Officially not recommended for use in real business, but commonly used when writing component libraries)
  • $refs gets the component instance
  • The envetBus sibling can use the event bus approach for data transfer in this case
  • Vuex status management

Vue responsive principle

The whole idea is data hijacking + observer mode

Attributes are internally hijacked using object.defineProperty (only existing attributes are hijacked) via the defineReactive method, while arrays are done by overriding array methods. When a page uses a corresponding attribute, each attribute has its own DEP attribute, which stores the watcher it depends on (dependent collection). When the attribute changes, the corresponding Watcher will be notified to update (distributed update).

The relevant codes are as follows

Class Observer {// Constructor (value) {this.walk(value); } walk(data) {let keys = object.keys (data); for (let i = 0; i < keys.length; i++) { let key = keys[i]; let value = data[key]; defineReactive(data, key, value); Function defineReactive(data, key, value) {observe(value); function defineReactive(data, key, value) {observe(value); // Recursion key // -- if the value is still an object, the odefineReactive loop continues until the value is not an object. Object.defineproperty (data, key, {get() {console.log(" get value "); Return value; return value; }, set(newValue) { if (newValue === value) return; Console. log(" Set value "); Value = newValue; }}); } export function observe (value) {/ / and if the Object or array of attributes to hijack the if (Object. The prototype. ToString. Call (value) = = = "[Object Object]" || Array.isArray(value) ) { return new Observer(value); }} Copy the codeCopy the code

Vue nextTick principle

The callbacks in nextTick are deferred callbacks that are executed after the next DOM update cycle ends. Use this method immediately after modifying the data to get the updated DOM. The main idea is to invoke asynchronous methods to execute nextTick wrapped methods in a microtask-first manner

The relevant codes are as follows

let callbacks = []; let pending = false; function flushCallbacks() { pending = false; For (let I = 0; i < callbacks.length; i++) { callbacks[i](); } } let timerFunc; // Define asynchronous methods that gracefully degrade if (typeof Promise! Const p = promise.resolve (); timerFunc = () => { p.then(flushCallbacks); }; } else if (typeof MutationObserver ! == "undefined") {// let counter = 1; const observer = new MutationObserver(flushCallbacks); const textNode = document.createTextNode(String(counter)); observer.observe(textNode, { characterData: true, }); timerFunc = () => { counter = (counter + 1) % 2; textNode.data = String(counter); }; } else if (typeof setImmediate ! Setimerfunc = () => {setImmediate(flushCallbacks); }; } else {setTimeout timerFunc = () => {setTimeout(flushCallbacks, 0); }; } export function nextTick(cb) {// In addition to rendering watcher, the nextTick is collected in the array callbacks.push(cb); if (! Pending) {// If the nextTick is called multiple times, it will only execute one async call until the async queue is empty and then change the flag to false pending = true; timerFunc(); }} Copy the codeCopy the code

Principle of Vue diff

Routing Principle Features of history and Hash routing modes

Hash pattern

  1. The value of location.hash is exactly what comes after the # in the URL. It’s nice to see that the hash appears in the URL, but it’s not included in the HTTP request. It doesn’t affect the back end at all, so changing the hash doesn’t reload the page.
  2. You can add listening events for changes to the hash
window.addEventListener("hashchange", funcRef, false); Copy the codeCopy the code

Each change to the hash (window.location.hash) adds a record to the browser’s access history. Using the above features of the hash, we can implement the front-end routing “update the view without rerequesting the page” function

Features: Good compatibility but not beautiful

The history mode

Takes advantage of the new pushState() and replaceState() methods in the HTML5 History Interface.

These two methods apply to the browser’s history station and provide the ability to modify the history in addition to the existing back, Forward, and Go methods. The two methods have a common feature: when they are called to modify the browser history stack, the browser does not refresh the page even though the current URL has changed, which provides the basis for single-page application front-end routing “update the view without rerequesting the page.”

Features: Although beautiful, but refresh will appear 404 needs to be configured on the back end

Handwritten Vue. Extend implementation

// src/global-api/initExtend.js import { mergeOptions } from ".. /util/index"; export default function initExtend(Vue) { let cid = 0; Extend = function (extendOptions) {// Create a constructor for the subclass and call the initialization method const Sub = function VueComponent(options) { this._init(options); // Call Vue initializer}; Sub.cid = cid++; Sub.prototype = Object.create(this.prototype); / / subclass prototype points to the parent class Sub. The prototype. The constructor = Sub; //constructor points to yourself sub. options = mergeOptions(this.options, extendOptions); // merge your own options with your parent's Options Return Sub; }; }Copy the code

Vue-router Whether pushState and replaceState route methods trigger the popSate event

The answer is: no

PushState and replaceState

HTML5’s new interface allows you to change urls (with cross-domain restrictions) without refreshing the page, a powerful feature that was later used in single-page applications such as jue-router and React-router-dom.

Note: just by changing the url, the page does not actually jump and no new content is retrieved, essentially the page remains the same

window.history.pushState(state, title, targetURL); @ status object: indicates the information sent to the destination route. It can be empty. @ Page title: is not supported by all browsers and can be filled with a blank string. If you don't pass the, that is, add data to the current url window. History. ReplaceState (state, title, targetURL); @ is similar to pushState, but replaces the current URL without record copying code in historyCopy the code

The popState event is emitted when the back or forward buttons are clicked (or when the history.back(), history.forward(), or history.go() methods are called)

Note: Using history.pushState() or history.replacEstate () does not trigger the popState event

nodejs

Nodejs common module

  • path
  • fs
  • HTTP, url
  • express
  • koa
  • mongoose
  • process
  • cookie, session
  • Crypto encryption related
  • os

Koa middleware idea, Onion model

class Middleware { constructor() { this.middlewares = []; } use(fn) { if(typeof fn ! == 'function') { throw new Error('Middleware must be function, but get ' + typeof fn); } this.middlewares.push(fn); return this; } compose() { const middlewares = this.middlewares; return dispatch(0); function dispatch(index) { const middleware = middlewares[index]; if (! middleware) {return; } try{ const ctx = {}; const result = middleware(ctx, dispatch.bind(null, index + 1)); return Promise.resolve(result); } catch(err) { return Promise.reject(err); }}}} // Use const middleware = new middleware (); middleware.use(async (ctx, next) => { console.log(1); await next(); console.log(2); }); middleware.use(async (ctx, next) => { console.log(3); await next(); console.log(4); }); middleware.compose(); // 1 3 4 2 copy the codeCopy the code

Differences between Express and KOA

  1. Coding style: Express uses callback function style, KOA1 uses Generator, koA2 (default) uses await, which is more elegant in style. Koa is more closely integrated with ES6 and 7.
  2. Error handling: Express uses error-first handling in callbacks. Deep-level exceptions cannot be caught, so errors must be handled in each layer of callbacks. Koa uses try catch to catch errors and uploads errors to handle errors uniformly.
  3. Koa removed the router, View and other functions built into Express, making the framework itself lighter.
  4. The Express community is large and relatively document-rich, and the KOA community is small;

Data structures are classic interview questions

1. The difference between arrays and linked lists.

Logically, arrays must be implemented at a fixed length and cannot accommodate dynamic data increments, meaning that the size of an array cannot be changed once defined. As data increases, it may exceed the number of elements originally defined; When data is reduced, memory is wasted; Linked list dynamically allocates storage, which can adapt to the situation of dynamic increase and decrease of data, and can easily insert and delete data items.

From a memory storage perspective; Arrays allocate space from the stack (created on the heap with new), which is fast and convenient for programmers, but has little freedom; Linked lists allocate space from the heap, which has a lot of freedom but is cumbersome to manage.

From the access class, arrays are contiguous in memory, so they can be accessed using subscript indexes. A linked list is a chain storage structure. When accessing elements, it can only be accessed from front to back in a linear manner, so the access efficiency is lower than that of an array.

2. Describe the quicksort process

1) Select a base element, usually the first or last element,

2) Divide the records to be sorted into two independent parts through a sort, where the element values of some records are smaller than the base element values. The other records element values greater than the reference value.

3) The base element is in the correct position after it is sorted

4) Then continue sorting the two parts of the records in the same way until the whole sequence is in order.

3. Quicksort improvements

Quicksort is recursively called only for subsequences of length greater than k, making the original sequence basically ordered, and then the entire basically ordered sequence is sorted by insertion sort algorithm. Practice shows that the time complexity of the improved algorithm is reduced, and the performance of the improved algorithm is the best when k is about 8.

How to select a primitive

For the divide-and-conquer algorithm, if the algorithm can be divided into two equal length sub-sequences each time, then the efficiency of the divide-and-conquer algorithm will reach the maximum. That said, the choice of benchmark is important. The method of selecting the datum determines the length of the two subsequences after two segmentation, which has a decisive influence on the efficiency of the whole algorithm. Ideally, the datum chosen is one that splits the sequence into two equally long subsequences.

Method 1 fixed the datum

If the input sequence is random, the processing time is acceptable. If the array is already ordered, this is a very bad split.

Method 2 random reference element

This is a relatively safe strategy. Since the position of the datum is random, the resulting segmentation will not always be inferior. If the entire array is equal, which is still the worst case, the time is O(n^2). In fact, the probability of randomized quicksort getting the theoretical worst case is only 1/(2^n). So randomized quicksort can achieve O(nlogn) expected time complexity for most input data.

Method 3: Take the middle number

The reason for introduction: although the probability of bad segmentation is reduced when randomly selecting the benchmark, it is still O(n^2) in the worst case. To alleviate this situation, the selection of the benchmark among three numbers is introduced.

Analysis: The best partition is to divide the sequence to be sorted into equal length subsequences, the best state we can use the middle value of the sequence, that is, the N/2 number. However, this is difficult to calculate and can significantly slow down quicksort. Such an estimate of the median can be obtained by randomly selecting three elements and using their median as the baseline. In fact, randomness doesn’t help much, so it’s common practice to use the median of the three elements on the left, right, and center as the base element.

Stability:

Stability of sorting algorithm: if there are multiple records with the same keyword in the sequence to be sorted, the relative order of these records remains unchanged, the algorithm is stable; If the relative order of records changes after sorting, the algorithm is said to be unstable.

Stable sorting algorithms: bubble sort, insertion sort, merge sort and radix sort

Not stable sorting algorithms: selection sort, quicksort, Hill sort, heap sort

Selection sorting algorithm criteria:

Generally speaking, the following four factors need to be considered:

Let the number of elements to be sorted be n.

1) When n is large, the sorting method with time complexity O(nlog2n) should be adopted: quicksort, heap sort or merge sort.

2) When n is large, the memory space is allowed and stability is required: merge sort

3) When n is small, direct insertion or direct selection sort can be used.

Direct insert sort: When elements are ordered, direct insert sort greatly reduces the number of comparisons and moves.

Direct selection sort: the elements are ordered. If stability is not required, select direct selection sort

5) The traditional bubble sort is generally not used or not directly used.

6) Radix sort it is a stable sorting algorithm, but there are certain limitations: 1, the keyword can be decomposed. 2, the record of the keyword number is less, if dense better 3, if it is a number, the best is unsigned

5. Improvement of bubble sort algorithm

1. Set a symbolic variable pos that records the last swap position in each sort run. Since all the records after the POS position have been swapped in place, it is only necessary to scan the POS position in the next sorting.

2. In traditional bubble sort, only one maximum value or minimum value can be found in each sort operation. We consider that we can get two final values (the largest value and the smallest value) at one time by bubbling forward and backward twice in each sort operation, thus reducing the number of sort trips almost by half.

6. Adjacency matrix and adjacency list

Adjacency matrix notation: Store all points in a one-dimensional array and weights of edges between vertices in a two-dimensional array

Adjacency list representation: The vertices in a graph are stored in a one-dimensional array, and all the adjacencies of each vertex VI in the graph form a single linked list

contrast

1) In the representation of adjacency matrix, the adjacency matrix of undirected graph is symmetric. The sum of the number of valid elements in the ith row or column of the matrix is the degree of the vertex.

In a digraph, the sum of the ith row valid elements is the vertex’s exit degree, and the sum of the ith column valid elements is the vertex’s entry degree.

2) In the representation of an adjacency list, the two times that the same edge of an undirected graph is stored in the adjacency list. If you want to know the degree of a vertex, you just have to figure out the number of nodes in the linked list.

Each edge in a directed graph appears only once in the adjacency list, so to find the degree of vertex, we only need to traverse the corresponding linked list. Finding the degree requires traversing the list of other vertices.

3) Advantages and disadvantages of adjacency matrix and adjacency list:

The advantage of adjacency matrix is that it can quickly determine whether there are edges between two vertices, and can quickly add or delete edges. The disadvantage is that if there are fewer edges between vertices, it wastes space. Because this is a matrix for n∗n.

The advantage of adjacency list is that it saves space and stores only the edges that actually exist. The disadvantage is that if you care about the degree of the vertices, you may need to traverse a linked list.

7. Are loops more efficient than recursion?

Recursion and looping are completely interchangeable. It is not entirely conclusive to say that cyclic efficiency is more efficient than recursive efficiency.

2.1 Recursive algorithm:

Advantages: The code is concise, clear, and easy to verify correctness.

Disadvantages: Its operation requires a large number of function calls, if the call layer is deep, need to add additional stack processing (and stack overflow may occur), such as parameter passing need to push the stack, will have a certain impact on the execution efficiency. However, for some problems, it would be extremely ugly code to not use recursion. After compiler optimization, there is a very good efficiency optimization for multi-call function processing, not necessarily less efficient than loops.

2.2 Cyclic algorithm:

Advantages: fast speed, simple structure.

Cons: Doesn’t solve every problem. Some problems are suitable for recursion rather than looping. Use loops if they are not difficult to use.

8. Methods to resolve hash conflicts

A Hash table (also called a Hash table) is a data structure that can be accessed directly based on Key values.

1) Linear detection method

2) Square detection method

3) Pseudo-random sequence method

4) Zipper method

9, KMP algorithm: in a string to find whether to contain the target matching string. The main idea is to slide the substring to an appropriate position in each comparison. When a mismatch occurs, instead of moving right one bit, you move (the length of the current match – the partial match value of the current match substring) bits.

10, B tree

According to the characteristics of the class B tree, more than an order of class B tree structure, and then in as much as possible on the node to store information, ensure the layer number of less as far as possible, so that later we can find information faster, disk I/O operations are less, and class B tree is balanced tree, the height of each node to the leaf node is the same, it also ensures that each query is stable.

The difference between B tree and B+ tree, take an m – order tree as an example.

  1. The number of keywords varies; The branch node of B+ tree has M keywords, and its leaf node also has M, and its keyword only plays an index role. However, although B tree also has M child nodes, it only has M-1 keywords.
  2. Storage location is different; The data in a B+ tree is stored in the leaf node, that is, the data of all the leaf nodes combined is complete data, but the data in a B+ tree is stored in each node, not only in the leaf node.
  3. The structure of branch nodes is different; The branch nodes of the B+ tree only store the key information and the Pointers to the children (the Pointers here refer to the offset of the disk block), which means that the internal nodes only contain the index information.
  4. Query different; A B tree ends when it finds a specific value, whereas a B+ tree ends when it finds the data in the leaf node through the index, which means that the search of a B+ tree takes a path from the root node to the leaf node.

summary

The above surface is just to play a role, front-end various interview questions emerge in endlessly, if only remember the answer is obviously not realistic, we must understand the principle, in order to use the same should be changed.

Because I have too many interviews to post one by one, I need more links to get 400 interview packages for free.