preface

To begin with, this melon is well aware of your pain point: the front interview knowledge is too miscellaneous, you always interview for the interview, forget to remember, remember and forget, cycle, this complaining.

Let bengua take you all back a little bit to remember the glory days of the periodic table when you were a student.

Hydrogen, helium, lithium, beryllium, boron, carbon, nitrogen, oxygen, fluorine, neon, sodium, magnesium, aluminum, silicon, phosphorus, sulfur, chlorine, argon, potassium, calcium, scandium, titanium, vanadium, chromium, Meng, iron, cobalt, nickel, copper, zinc……

Did we memorize the first 30 elements by rote? And the answer is no. Tactfully, we use tandem memorization.

It must be something like this or something like this:

First cycle: hydrogen helium ———— Gently Hi: gently say hello: Hi! Second cycle: lithium beryllium boron carbon nitrogen oxygen fluorine neon ———— your skin holding carbon egg raise milk: you are very skin, holding a handful of carbon in the hand. Third cycle: sodium, magnesium, aluminum, silicon, phosphorus, sulfur, chlorine, argon ———— The beauty leaves green teeth in Guilin: the beauty leaves green teeth in Guilin The fourth cycle: potassium, calcium, scandium, titanium, vanadium, chromium, Fierce iron, cobalt, nickel, copper, zinc ———— Jia Gaekeng Tai Fan ge Fierce iron bone crack sad: "Jagai" pit "too fan elder brother", lead to strong man iron man bone broken very sadCopy the code

Tandem associations are similar to binary chained associative memory in that they both help us achieve bi-brain learning and memory goals by imagining, creating, and making up stories. – the source

Do you have any? Ben melon remember particularly clearly, the above series of homophonic story can simply write a dog blood script. In particular, the simple words “that beauty (sodium magnesium aluminum)” seem to trigger puberty hormones. So, study can not be interested? Interest is the best teacher! It’s hard to forget!

So, this melon analogy domestication, will encounter their own high-frequency interview questionsSeries association methodCarried out “series” arrangement, in order to form a system, and everyone with good sharing.

The picture above!

  • This article brain map support: Processon
✍ points like writing is not easy to encourage 👍 your feedback 📑 my motivation 💪


A series:

What happens between entering the URL and loading the page?

This problem is the classic in the classic, can excavate the point very much, also very deep.

A picture is worth a thousand words

  • Original brain map, reproduced please explain the source

Link knowledge: URL parsing, DNS query, TCP handshake, HTTP request, browser processing return packet, page rendering

Serial memory: a total of six steps, merged into a single sentence to remember: UDTH, processing return and render.

“UDTH” is URL parsing, DNS query, TCP handshake, HTTP request,

“Process return plus render”, which means the browser processes the returned message, and render the page.

At the same time, bengua in the brain map marked each step may be investigated knowledge “key words”, really is a key point, not to be missed!

1. URL parsing

Uniform Resource Locator (URL), commonly known as URL, is used to locate resources on the Internet.

/ / sample from wikipedia hierarchical part ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ authority path ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ ┌ ─ ─ ─ ┴ ─ ─ ─ ─ ┐ abc://username:[email protected]: 123 / path/data? Key = value&key # 2 = value2 fragid1 └ ┬ ┘ └ ─ ─ ─ ─ ─ ─ ─ ┬ ─ ─ ─ ─ ─ ─ ─ ┘ └ ─ ─ ─ ─ ┬ ─ ─ ─ ─ ┘ └ ┬ ┘ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┬ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ └ ─ ─ ┬ ─ ─ ┘ scheme user information host port query fragments scheme - defines the type of Internet service. Common protocols include HTTP, HTTPS, FTP, and File. The most common type is HTTP, while HTTPS is used for encrypted network transmission. Host - defines the domain host (HTTP default host is WWW) domain - defines the Internet domain name, such as baidu.com port - defines the port number on the host (HTTP default port is 80) path - Defines the path on the server (if omitted, The document must be in the root directory of the web site). Filename - specifies the name of the document/resource. Query - specifies the query parameter fragment - specifies the hash value after #, which is usually used to locate a locationCopy the code

More visible:

  1. URL RFC
  2. Wikipedia-URI

URL encoding

In general, urls can only use English letters, Arabic numerals, and certain punctuation marks. No other words or symbols can be used. This is mandatory in the URL RFC.

This means that if there are Chinese characters in the URL, they must be encoded and used. The trouble with RFC 1738 is that it doesn’t specify how to code it, leaving it up to the application (browser) to decide. This makes “URL encoding “a confusing area.

Teacher Ruan explained back in 2010: About URL coding – Ruan Yifeng

Here’s the bottom line: Browsers encode urls differently and cause confusion, so let’s say we use Javascript to pre-encode urls before submitting them to the server. Because the output of Javascript is always consistent, this ensures that the server gets the same format for the data.

We often use: encodeURI(), encodeURIComponent(); The former encodes the entire URL in UTF-8, while the latter encodes parts of the URL.

Can you clearly explain the meanings and relationships of ASCII, Unicode, UTF-8, GBK?

Maybe we don’t know much about the things we see and use.

type meaning
ASCII 8 bits a byte,1 byte for a character. That is, 2 ** 8 = 256, so the MAXIMUM number of ASCII characters can be 256.
Unicode Commonly known as universal code, to unify all languages into a code. Solve the limitation of ASCII code and garbled problem. Unicode codes typically use two bytes to represent a character, and more obscure use four bytes to represent a character.
UTF-8 “Variable-length encoding”. If English characters are used, ASCII encoding is adopted and takes up one byte. If it is a common character, it takes up three bytes. If it is a rare character, it takes up four to six bytes.
GBK In the domestic version, one Chinese character == two bytes is one byte in English

Strong cache, negotiated cache

In the first place, we put the strong cache and negotiated cache in the third step, “HTTP request”. Later, we learned that if the strong cache is hit, the DNS resolution step is no longer required. So I put it here. Is the browser strong cache based on IP or domain name?

Strong cache and negotiated cache are required questions. The specific process is as follows:

  1. When the browser loads the resource, it determines whether the request hit the strong cache based on the expires and cache-control headers. If yes, the browser reads the resource directly from the cache and does not send the request to the server.

    Expires: Specifies the HTTP/1.0 period, which is determined by comparing the local time to the server time.

    Cache-control: indicates the HTTP/1.1 period. The value is determined by the relative time. For example, set max-age in seconds.

  2. If a strong cache is not hit, the browser must send a request to the server to verify that the resource is a hit with Etag and last-Modified-if. If it is, the server returns the request (304), telling the browser to read the data from the cache.

    [ETag, if-none-match] Pair: ETag is what the server returns to the browser, if-none-match is what the browser requests from the server. By comparing the two, they record the unique identification of the file generation.

    [last-modified, if-modified-since] : Modified-since is what the server returns to the browser, and if-modified-since is what the browser requests from the server. By comparing the two, they record the time of last modification.

    Note: ETag has a higher priority than last-Modified. Most Web servers have negotiation caching enabled by default, with both ETag, if-none-match, and last-modified, if-modified-since enabled.

  3. If neither of the above hits, the resource is loaded directly from the server.

In summary, both strong cache and negotiated cache load resources from the client cache, rather than load resource data from the server. The difference is that the strong cache does not send the request to the server. The negotiation cache sends the request to the server for comparison and determines whether the request is hit.

  • Borrow a flow chart, not yet found the true source, retain the reference to the pit.

Another important point is the classification of cache-control values, such as “no-cache”, “no-store”, and “private”. Here only temporarily listed for preliminary interpretation.

  1. No-cache: Skip the current strong cache and send HTTP requests, that is, enter the negotiation cache phase directly.
  2. No-store: Does not perform any form of caching.
  3. Private: In this case, only the browser can cache. The intermediate proxy server cannot cache.

More visible:

  • Cache-Control – MDN
  • Caching (2) — Browser caching mechanisms: strong cache, negotiated cache #41

2. DNS query

Recursive query

DNS parses the URL (from right to left) to find the corresponding IP address

// For example: find the IP address of www.google.com (the real address is www.google.com.) : Root DNS server -> com top-level DNS server -> google.com DNS server -> IP address corresponding to www.google.com. ->.com -> google.com. -> www.google.com.Copy the code

This is a recursive query process.

For more knowledge about the root domain name, see root Domain name knowledge – Ruan Yifeng.

DNS cache

Remember: Where there is DNS, there is A DNS cache.

DNS has multiple levels of caching, sorted by browser distance, including the following:

Browser cache 2. System cache 3. Router cache 4. Root DNS cache 6. Top-level DNS cache 7. Primary DNS cache.

View the cache:

  1. Chrome ://net-internals/# DNS

  2. Win +R => CMD => ipconfig /displaydns

DNS load balancing

The DNS load balancing technology is implemented by configuring multiple IP addresses for the same host name on a DNS server. When replying to a DNS query, the DNS server returns different resolution results based on the IP addresses recorded in the DNS file for each query, so that clients can access different machines. Different clients access different servers, so as to achieve the purpose of load balancing. – wikipedia

TCP handshake

After DNS resolves the IP that returns the domain name, it is up to the browser to establish a TCP connection with that IP.

Voice outside words: THE relevant knowledge of TCP in the university foundation course “computer network” have, this melon heart bitter: come out mix sooner or later is to return……

TCP/IP model: link layer – network layer – transport layer – application layer.

In contrast, OSI (Open Systems Interconnection Model) should not be forgotten. It is generally considered that the top three layers of the OSI model (application layer, presentation layer and session layer) correspond to the application layer in the TCP/IP model. wiki

In the TCP/IP model, commonly used protocols such as HTTP/HTTPS/SSH are all at the application layer.

Three handshakes and four waves

Three-way Handshake is when a TCP connection is established with a total of Three packets sent by the client and server.

The three handshakes were just like the early phone calls: 1. A: Can you hear me? B: Yes, I can. How about you? 3. A: I heard that too. Then we can have a real conversation.

1. First handshake (SYN=1, SEq =x): The client sends a TCP PACKET with the SYN flag at position 1, indicating the server port to which the client intends to connect, and the initial Sequence Number x, which is stored in the Sequence Number field of the packet header. After the sending is complete, the client enters the SYN_SEND state. 2. Second handshake (SYN=1, ACK=1, SEq =y, ACKnum=x+1): The server sends back an ACK packet. That is, the SYN flag bit and ACK flag bit are both 1. The server selects its ISN sequence Number, places it in the Seq field, and sets the Acknowledgement Number to the ISN plus 1 (X+1) of the client. After the sending is complete, the server enters the SYN_RCVD state. 3. After the third handshake (ACK=1, ACKnum=y+1), the client sends an ACK packet with the SYN flag bit being 0 and the ACK flag bit being 1. The CLIENT sends an ACK packet with the serial number field +1 sent by the server in the SPECIFIED field. The client enters the ESTABLISHED state. When the server receives the packet, the client also enters the ESTABLISHED state. The TCP handshake ends.Copy the code

Four-way handshake is a TCP connection that takes Four packets to send.

Four waves like the teacher’s scene: 1, the students said: teacher, class is over. Teacher: Ok, I know, I finish this point. Teacher: Ok, that’s all. Class is over. 4, students: Thank you, teacher, goodbye.

1. First wave (FIN=1, seq=x) Suppose the client wants to close the connection. The client sends a packet with the FIN flag of 1 to indicate that it has no data to send, but it can still accept data. After the sending is complete, the client enters the FIN_WAIT_1 state. 2. Second wave (ACK=1, ACKnum=x+1) The server acknowledges the client's FIN packet and sends an acknowledgement packet indicating that it has received the client's request to close the connection, but is not ready to close the connection. After sending, the server enters the CLOSE_WAIT state. After receiving the acknowledgement packet, the client enters the FIN_WAIT_2 state and waits for the server to close the connection. 3. After the third wave (FIN=1, seq=y), when the server is ready to close the connection, the server sends a request to the client to close the connection. Set FIN to 1. After the sending is complete, the server enters the LAST_ACK state and waits for the last ACK from the client. 4. Fourth wave (ACK=1, ACKnum=y+1) After receiving the shutdown request from the server, the client sends an acknowledgement packet and enters the TIME_WAIT state to wait for a possible ACK packet to be retransmitted. After receiving the acknowledgement packet, the server closes the connection and enters the CLOSED state. If the client does not receive an ACK from the server after a fixed period of time (2MSL, 2 Maximum Segment Lifetime), it considers that the server has CLOSED the connection and enters the CLOSED state.Copy the code

If you ask me, do I remember the details of the three handshakes and four waves? Bengua replied: It is necessary to enter the big factory.

Gifs source: Two GIFs – fully understand TCP’s three handshake and four wave

Flow control (sliding window)

In order to increase the throughput of the network, you want to send packets together to achieve “flow control”, when the “sliding window” protocol was born.

Sliding Windows allow the sender to send multiple segments of data before receiving an acknowledgement from the receiver. The window size determines the maximum number of data segments that can be transmitted at one time before destination confirmation is received. The larger the window size, the more data segments the host can transmit at a time. When the host transmits the number of data segments of the window size, it must wait for the confirmation before it can transmit the following data segments.

The size of the window is variable during the connection between the two communication parties. The two communication parties can dynamically modify the size of the window through negotiation. The only reason to change the size of the window is the size of the receiver buffer.

Congestion control

If demand > supply, there will be congestion

In Congestion Window, Slow Start, Fast Retransmission, and Fast Recovery, dynamically resolve the problem.

TCP uses a variety of congestion control strategies to avoid avalanche congestion. TCP maintains a “congestion window” for each connection to limit the total number of unacknowledged packets that may be transmitted end-to-end. This is similar to the sliding window used in the TCP flow control mechanism. TCP uses a “slow start” mechanism to increase the size of the congestion window after a connection is initialized or times out. It typically starts at twice the Maximum segment size (MSS), and despite being called “slow start”, the initial value is quite low, but it grows very quickly: When each segment is confirmed, an MSS is added to the congestion window, so that the congestion window can efficiently double within each round trip time (RTT). — TCP Congestion Control – Wikipedia

There are too many things in sliding window (flow control) and congestion control for Bengua to understand and remember.

Recommended Reading:

  • This article takes you to understand TCP’s “sliding window” protocol
  • TCP traffic control and congestion control

4. HTTP request

HTTP is the data communication foundation of the World Wide Web – Wikipedia

An HTTP request packet consists of three parts: request line, request header, and request body.

An HTTP response packet also consists of three parts: the status code, the response header, and the response packet.

HTTP, HTTPS

What’s the difference between HTTP and HTTPS?

HTTP packets are sent wrapped in TCP packets. After receiving THE TCP packets, the server unpacks the PACKETS and extracts the HTTP packets. However, there are risks in this process. The HTTP packets are in plain text. If they are intercepted, some information may be leaked.

You can solve this problem by encrypting the HTTP before entering the TCP packet. The HTTPS protocol is essentially HTTP + SSL(or TLS). Before HTTP packets enter TCP packets, SSL is used to encrypt HTTP packets. In the hierarchy of the network, it lies between the HTTP and TCP protocols.

HTTP2

Http2 is fully HTTP /1.x compliant and adds four major new features:

  1. Binary framing: HTTP /1.x is a text protocol, while HTTP2 is a binary protocol.
  2. Header compression: HTTP /1.x request headers are basically unchanged. Http2 proposes an HPACK compression method to reduce the amount of traffic consumed by HTTP headers per request.
  3. Server push: The server proactively pushes data to the client.
  4. Multiplexing: HTTP /1.x, each HTTP request will establish a TCP connection; Http2, all requests share a TCP connection.

For more information, see HTTP2 details

The GET and POST

Intuitive differences:

  1. GET is used to GET data and POST is used to submit data.
  2. The GET parameter is limited in length (the maximum value is 2M, depending on browser and server restrictions), while the POST parameter is unlimited.
  3. The data for a GET request is appended to the URL with a “?” Split, multiple parameters are connected with “&”, and POST requests put the requested data in the HTTP request body. Can be caught bag.
  4. GET requests are saved in the browser history and possibly in the WEB server logs.

Hidden differences (browser differences exist) :

  1. GET generates a TCP packet. POST generates two TCP packets.

Learn more:

RESTful API Design Guide – Ruan Yifeng

Keep-Alive

We all know that keep-alive is used to avoid reestablishing connections.

Most browsers currently use http1.1, which defaults to keep-alive requests, so whether a complete keep-alive connection can be completed depends on the server Settings.

Keep-alive: timeout=5, Max =100, meaning that the TCP channel can be kept Alive for 5 seconds, Max =100, meaning that the long connection will be disconnected after receiving a maximum of 100 requests.

The HTTP server does not automatically disconnect when sending data in keep-alive mode, so it cannot return EOF (-1).

This raises the question: When HTTP is in Keepalive mode, how does the client know that the server’s data has been completed when the client requests it?

  1. Use the message header field conent-length: conent-length indicates the Length of the entity content. The client can judge whether the data is received according to this value.

  2. Use the header field transfer-encoding: If the page is dynamic, it is impossible for the server to know the size of the content in advance, so the data can be transferred using transfer-encoding: Chunk mode. If you want to generate data and send it to the client at the same time, the server needs to use “transfer-encoding: chunked” instead of content-length. Chunked encoded data has an empty chunked block at the end, indicating the end of the data transfer

Transfer-encoding: chunk: Transfer Encoding: Chunk: Transfer Encoding: Chunk

Reference:

  • Keep-Alive – MDN
  • HTTP long and short connections

The browser processes the returned message

Status code

1xx: indicates that the request has been received and processing continues.

2xx: succeeded – Indicates that the request is successfully received, understood, and accepted.

3xx: Redirection – further action must be taken to complete the request.

4xx: Client error – The request has syntax errors or the request cannot be implemented.

5xx: Server error – The server failed to implement a valid request.

The common status codes are :200, 204, 301, 302, 304, 400, 401, 403, 404, 422, 500.

Split return header and return body

HTTP keep-alive: HTTP keep-alive: HTTP keep-alive: HTTP keep-alive

Detect end of HTTP request body-stackOverflow

Answer:

1. If the client sends a message with Transfer-Encoding: Chunked, you will need to parse the somewhat complicated chunked transfer encoding syntax. You don not really have much choice in  the matter -- if the client is sending in this format, you have to receive it. When the client is using this approach, you can detect the end of the body by a chunk with a length of 0. 2. If the client instead sends a Content-Length, you must use that.Copy the code

That is: How do I get the HTTP return body?

  1. The header is read up to \r\n\r\n (two line feeds), i.e. the entire header;

  2. If transfer-encoding: Chunked is returned, it is read until an empty Chunked block is encountered, and then it ends.

  3. If content-length is returned, the read starts at the end of the request header and calculates the content-length Length in bytes.

  4. In other cases, wait to return.

Learn more: HTTP Response

Local data store

  1. Cookie: 4K. You can manually set the expiration period.
  2. LocalStorage: 5M. The value persists unless manually cleared.
  3. SessionStorage: 5M. It cannot be accessed across labels. The page will be cleared after closing.
  4. IndexedDB: browser-side database with unlimited capacity and will exist unless manually cleared.
  5. Web SQL: Relational database, accessed through SQL statements (deprecated).

Browser cache location

In order of priority:

  1. Service Worker: Essentially a Web Worker, a script that runs independently of a web page.
  2. Memory Cache: Memory Cache refers to the Memory Cache, which is the fastest in terms of efficiency.
  3. Disk Cache: Disk Cache is the Cache stored on disks. It is slower than memory Cache in terms of access efficiency, but it has advantages in storage capacity and storage duration.
  4. Push Cache: This Cache is HTTP/2 content.

More:

  • Service worker static resource offline caching practice
  • HTTP/2 push is tougher than I thought

Offline cache:

<html lang="en" manifest="offline.appcache">
Copy the code

Html5-offline Cache (Application Cache)

Note: “browser cache location” and “offline cache” are related, just have a concept/impression.

6. Page rendering

CssTree+DomTree

This is what Ben knows you know:

dom tree + css tree = render tree => layout =>painting?

But have you really figured it out?

HTML → DOM tree transformation process:

  1. Decoding: The browser reads the raw bytes of HTML from disk or the network and converts them to the corresponding characters according to the specified file encoding format (such as UTF-8)
  2. Tokenization: The browser converts characters into various exact tokens specified by the W3C HTML5 standard, such as “”, “”, and other strings within Angle brackets. Each token has a special meaning and its own set of rules
  3. Lexical analysis: Generated tokens are transformed into objects that define their properties and rules
  4. DOM tree construction: finally, due to the HTML tag defines the relationship between the different labels (some tags nested in other tags), objects created links to each other in a tree data structure, a tree data structure also captures the original label definition of parent-child relationships: HTML object is the parent body object, the body is the object’s parent object p and so on

CSS → CSSOM tree transformation process is similar to the above

CSSOM outputs only the nodes that contain the styles, and the final output is:

Generate a Render Tree, compute visible nodes and styles

  1. It does not include Header, script, meta and other invisible nodes
  2. Some nodes that are hidden by CSS will also be ignored in the render tree, such as nodes where display: None rule is applied, while visibility: hidden is only visually invisible and still occupies space and will not be ignored.

Layout: Calculate the position and size of each node in the screen according to the box model

Painting: Follow the calculated rules and use the graphics card to draw the content onto the screen.

Reflux, redraw

Return:

Backflow occurs when the position and size of visible nodes change

Redraw:

When changing an element’s background color, text color, border color, and so on does not affect its surrounding or internal layout properties, part of the screen is redrawn, but the element’s geometric size remains the same.

Here bengua asks two more questions.

Q1: When does the browser send a request to the server to obtain CSS and JS external files?

A1: An external link is encountered while parsing the DOM. If there is a connection, the download request is triggered immediately.

Q2: CSSOM DOM JavaScript blocking relationship?

A2: CSSOM DOM does not affect each other, JavaScript will block the building of the DOM tree, but the HTML before JS can parse into the DOM tree normally, CSSOM building will block the execution of JavaScript. Doubt this sentence?

  • The blocking of CSS loading:
  1. CSS loading does not block DOM tree parsing

// DOM parsing and CSS parsing are two parallel processes, so this explains why CSS loading does not block DOM parsing.

  1. CSS loading blocks rendering of the DOM tree

// Since the Render Tree is dependent on the DOM Tree and the CSSOM Tree, he must wait until the CSSOM Tree is built and the CSS resource is loaded (or failed to load the CSS resource) before he can Render. Therefore, CSS loading blocks Dom rendering.

  1. The CSS load blocks the execution of the js statement that follows

// Since JS may manipulate previous Dom nodes and CSS styles, the browser maintains the order of CSS and JS in HTML. As a result, the stylesheet is loaded and executed before any subsequent JS execution. So the CSS blocks the subsequent js execution.

Reference reading:

  1. Does CSS loading block?
  2. Browser page rendering process comb

Comprehensive supplement

Web Performance optimization

  • Yahoo 35 catch rules

Series 2:

Cliche. Can you talk about closures?

If you think this question is easy, you can finish it in one or two sentences? That really floats on the surface. This question actually one or two days say not over! It can involve most of the knowledge of JS principles. It is a real “motif”.

A picture is worth a thousand words

  • Original brain map, reproduced please explain the source

Connecting the dots: closures, scopes, prototype chains, JS inheritance.

Tandem memory: This question is not like “What happens between entering the URL and loading the page?” The latter “series points” are advanced by solution steps. And the “connection point” here, more is in you, I have you, before and after each other complement, improve each other. When you finish, there will be a feeling of “all things return to live”.

To memorize in a five-character poem:

The closure scope prototype considers the inheritance of the eight methods are described

A, closures

Closure meaning

In a word.

A lexical context in which another function can access its internal variables and another function is called externally is called a closure.

  • Function:
  1. Reading variables inside a function; (Private variables, do not pollute the global)
  2. Keep variables always in memory.

Closure application

  • Most classic test questions
for(var i = 0; i < 5; i++){ (function(j){ setTimeout(function(){ console.log(j); }, 1000); })(i); } console.log(i);Copy the code

Garbage collection mechanism

  • Js garbage collection mechanism: tag cleanup and reference counting.

Mark clear in short is variable stored in memory, when the variables into the execution environment, garbage collector will add tags to it, this variable from the execution environment, mark it as “clean”, cannot track, not by other object references, or the two objects refer to each other, not to be the third object references, and then by the garbage collector, free memory space.

Shaking and throttling functions

  • Image stabilization
function debounce(fn, delay) { var timer; // Maintain a timer return function () {var _this = this; // This var args = arguments; if (timer) { clearTimeout(timer); } timer = setTimeout(function () { fn.apply(_this, args); // Use apply to point to the object calling debounce, which is equal to _this.fn(args); }, delay); }; }Copy the code
  • The throttle
function throttle(fn, delay) { var timer; return function () { var _this = this; var args = arguments; if (timer) { return; } timer = setTimeout(function () { fn.apply(_this, args); timer = null; }, delay)}}Copy the code

2. Scope

Global scope

  • JS code written directly in a script tag is in global scope;
  • The global scope is created when the page is open and destroyed when the page is closed.
  • There is a global object in the global scope, window, which represents a browser window. It is created by the browser and we can use it directly.
  • In the global scope, created variables are saved as properties of the Window object;
  • All functions created are saved as methods on the Window object;
  • Variables in the global scope are global variables and can be accessed from any part of the page.

We can try printing directly from the console, as mentioned above:

Function scope (local scope)

  • Variables are declared inside a function and belong to a local scope.
  • Local variables: can only be accessed inside a function.
  • Local variables only operate within a function, so different functions can use variables with the same name.
  • Local variables are created at the start of function execution and are automatically destroyed after the function is finished.

Block-level scope

Block-level scope: Block-level scope refers to the use of if () {}; while ( ) { } …… These statements form a block of statements in which variables must be declared let or const, ensuring that variables in the block are not accessible to outsiders.

Note: Function scope is not directly related to block-level scope.

  • Const, let, var
  1. Const declarations cannot be changed, block level scope, and do not allow variables to be promoted.
  2. Let block-level scope that does not allow variable promotion.
  3. Var is not block-level scope and allows variables to be promoted.

The scope chain

When a function nesting function occurs, a scope chain occurs.

  • The rules for traversing a chain of nested scopes are simple: the engine looks for variables starting at the current execution scope, and if it cannot find them, it continues the search up a level. When the outermost global scope is reached, the search stops whether it is found or not.
  • Local scopes (such as function scopes) can access variables and methods in the global scope, while global scopes cannot access variables and methods in the local scope.

To explain closures in terms of scope chains:

function outter() { var private= "I am private"; function show() { console.log(private); } // [[scope]] already determined: [outter context variable object, global context variable object] return show; } var ref = outter(); console.log(private); Private is not defined ref(); private is not defined ref(); private is not defined ref(); // Print I am privateCopy the code

In fact, we need to understand that functions are declared and called separately, and if we don’t understand this, many basic interview questions are prone to error.

  • Probe:

JavaScript Deep lexical scope and dynamic scope #3

Variable life cycle

The declaration of a variable means that we have allocated a space in memory to store it. This memory is the running memory of our computer, if we keep declaring variables and don’t free them. It takes up a lot of memory.

While c/ C ++ requires the programmer to manually free variable memory where appropriate, javascript and Java have a garbage collection mechanism (as described above).

There are two types of JS variables: global and local

  1. Life cycle of global variables: from the beginning of the program to perform creation, to the entire page closed, variables are recalled.
  2. Life cycle of a local variable: from the start of the function call to the end of the function call.

But there are times when we need to make the local variable’s lifetime longer, and that’s where closures are used.

Three, prototype chain

Examples and Prototypes

The invisible properties of a prototype object point to the display properties of the constructor that constructed it.

When an Object looks for its properties, it can’t find any, it looks for the properties of its constructor, and keeps looking up until it finds Object().

Determine the data type

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

So new is an object

Steps:

  1. Create a new object
  2. Assign the scope of the constructor to the new object (so this points to the new object)
  3. Execute the code in the constructor (add properties to the new object)
  4. Return new object

This points to the

This points to five rules:

  1. If the new keyword appears before the function being called, the JavaScript engine creates a new object, and this in the called function refers to the newly created function.
  2. If the function is triggered by apply, call, or bind, then this refers to the first argument passed to the function.
  3. If a function is a method of an object, and the object fires the function using a period symbol, then this refers to the object on which the function is a property of that object, i.e., this refers to the object to the left of the period
  4. If a function is called as FFI, it means that the function is not called in any of the above ways. This refers to the global object, which in the browser is window.
  5. If there is an accumulation of the above rules, the priority decreases from 1 to 4, and the point of this is determined according to the rule with the highest priority.

Reference: This points to the five principles of memory

  • This in the arrow function refers to: this in the arrow function is bound when the function is defined, not when it is executed.

More: Arrow function in JS with this

Bind, call, apply

  • call

The call() method receives the same first argument as the apply() method, with the exception that the remaining arguments are passed directly to the function. In other words, when using the call() method, the arguments passed to the function must be listed one by one.

function sum(num1 , num2){ return num1 + num2; } function callSum(num1 , num2){ return sum.call(this , sum1 , sum2); } console.log(callSum(10 , 10)); / / 20Copy the code
  • apply

The apply() method takes two arguments: one is the scope in which the function is run, and the other is an argument Array, which can be either an instance of Array or a Arguments object (array-like object).

function sum(num1 , num2){ return num1 + num2; } function callSum1(num1,num2){ return sum.apply(this,arguments); } function callSum2(num1,num2){return sum.apply(this,[num1,num2]); } console.log(callSum1(10, 10)); // 20 console.log(callSum2(10 , 10)); / / 20Copy the code

The difference between call and apply is that they pass arguments one by one, while the latter passes an array or class array of arguments

  • bind

The bind() method creates a new function, sets its this keyword to the supplied value when called, and provides a given sequence of arguments before any supply when the new function is called.

Handwritten deep copy

Light:

function clone(target) {
    let cloneTarget = {};
    for (const key in target) {
        cloneTarget[key] = target[key];
    }
    return cloneTarget;
};
Copy the code

Deep (recursion) :

function clone(target) { if (typeof target === 'object') { let cloneTarget = Array.isArray(target) ? [] : {}; for (const key in target) { cloneTarget[key] = clone(target[key]); } return cloneTarget; } else { return target; }};Copy the code

Read more: How to Write a Deep Copy of an Amazing Interviewer?

4. Js inheritance

Eight inheritance methods, see this article: eight inheritance schemes commonly used in JavaScript.

This melon does not do tautology, can list two or three key must remember.

Three series:

Can you talk about the Vue principle?

Let’s not pretend. Let’s show our cards. In fact, the directory structure of this article writing timeline in the “Vue(V2.6.11) ten thousand lines of source code generation gnaw, hard just!” Before this article. At that time is because of half-understand, just settle down to “raw gnaw source code”. Now the source is finished, the experience is really different. But there are too many details, so space is limited. Here, again, only the frames, highlights, and comment links are listed for memorization.

A picture is worth a thousand words

  • Original brain map, reproduced please explain the source

Series knowledge: Vue initialization and life cycle, virtual DOM, responsive principle, component compilation, Vue commonly used supplement, Vue family bucket.

Tandem memory: make up a rhyme, laugh.

V U E really easy to initialize a living virtual DOM good force responsive look carefully componentization everyone benefits the whole family bucket grinning will pack to earn 100 million

  • I invite you to adapt

A, init&render

Mount and initialize

What happens to new Vue()?

Vue is actually a class, and classes are implemented in Javascript using Function. Vue can only be initialized with the new keyword, and then the this._init method is called.

Initialization main implementation: Merge configuration (mergeOptions), initialize initLifecycle, initEvents, initRender, data, props, computed, watcher, and so on.

Refer to the flowchart as follows:

  • This diagram has less optimize in component compilation, possibly due to version differences. Vue2.4.4 source
  • Borrow the map, did not find the true source, retain the reference to the pit.

Instance lifecycle

The life cycle diagram, again, depends on the official website documentation. Remember that?

The following figure shows the life cycle of the instance. You don’t have to understand everything right away, but it will become more valuable as you learn and use it.

The annotated version:

Recommended: source code interpretation

Key notes:

  1. Both the beforeCreate and created functions are executed in the _init method during the instantiation of Vue. BeforeCreate and Created hooks are called before and after initState, which initializes props, data, methods, watch, and computed. BeforeCreate (props, data); beforeCreate (props, data); beforeCreate (functions); The created hook function does.
Vue.prototype._init = function (options? : Object) { // ... initLifecycle(vm) initEvents(vm) initRender(vm) callHook(vm, 'beforeCreate') // beforeCreate hook initState injections (vm) // resolve injections before data/props initState(VM) InitProvide (VM) // props callHook(vm, 'props ') // created hook //... }Copy the code
  1. BeforeMount hook function is executed before VNode is rendered by v._render (). Mounted hook is executed after VNode is patched to the real DOM by V._update (). (This is important)

  2. BeforeUpdate execution timing is called in the render Watcher’s before function. Update is executed when the flushSchedulerQueue function is called.

  3. BeforeDestroy and Destroyed hook functions are executed during the component destruction phase.

  4. The Activated and deActivated hook functions are custom hooks for keep-Alive components.

Key notes:

  1. In Vue2, all Vue components will eventually require the render method, whether we develop the component as a single file. Vue, or write el or template properties, which will eventually be converted to the Render method. Use to render the instance as a Virtual Node (Virtual DOM).

2. Virtual DOM

The biggest upgrade of Vue 2.0 compared to Vue 1.0 is the use of Virtual DOM.

vdom

Vdom is actually a JS object tree, which contains at least three attributes: tag, attrs, and children. The original operation on DOM nodes (the browser designed the DOM to be very complex) is turned into the operation on JS objects, speeding up the processing speed and improving performance.

The creation of a VNode is done by the createElement method.

Recommended reading: snabbDOM

diff & patch

In real code, the old and new trees are traversed in one depth, with each node marked. Each time a node is traversed, it is compared to the new tree, and any differences are recorded in an object. Diff algorithm is used to compare the differences, and then patch is called to apply to the real DOM. The process of patch is a process of patching.

photo

Diff algorithm is a process of cross comparison, which can be briefly summarized as: head to head comparison, tail to tail comparison, head to tail comparison, tail to head comparison.

For details on the entry-level DIff level, see LINK

photo

Note: The render function returns vDOM; patch generates the real DOM.

Three, the response principle

The official health picture, hillhouse.

Bengua has written in the article “a brief analysis of vue’s bidirectional binding principle”, and now it is a mood.

When you pass a normal JavaScript object to a Vue instance as the data option, Vue will iterate through all the properties of that object, Use object.defineProperty to turn all of these properties into getters/setters. Object.defineproperty is a non-shim feature in ES5, which is why Vue does not support IE8 and earlier browsers.

Publish Subscriber Mode (byte test)

class emit {
}
cosnt eeee =  new emit()
eeee.on('aa' , function() { console.log(1)})
eeee.on('aa' , function() {console.log(2)})
eeee.emit('aa')
//class emit{}
Copy the code

// Requires a handwritten publisher-subscription model

class Subject{ constructor () { this.observers =[] } add (observer) { this.observers.push(observer) } notify () { this.observers.map((item, index) => { item.update() }) } } class Observer { constructor (name) { this.name = name } update () { console.log("I`m "  + this.name) } } var sub = new Subject() var obs1 = new Observer("obs1") var obs2 = new Observer("obs2") sub.add(obs1) sub.add(obs2) sub.notify() // I`m obs1 I`m obs2Copy the code

What other JS design patterns do you know besides “publisher subscription”? Here to leave a pit, later to fill, too much……

Observe

The Observe function is used to monitor changes in data. It adds getters and setters to the properties of an object for dependency collection and dispatch updates:

Here is a clip of the source code, we can feel it:

export class Observer { value: any; dep: Dep; vmCount: number; // number of vms that has this object as root $data constructor (value: any) { this.value = value this.dep = new Dep() this.vmCount = 0 def(value, '__ob__', this) ... } walk (obj: Object) { ... } observeArray (items: Array<any>) { ... }}Copy the code

Do you think it is similar to the published subscriber model mentioned above? The Observer first instantiates the Dep object and then adds an instance of itself to the ob property of the data object value by executing the def function. The def function is a simple wrapper around an Object.defineProperty.

Dep

Dep is the core of the entire getter dependency collection.

Since there are multiple Watchers, Dep should be used to collect changes, manage them in a centralized manner, and then inform the corresponding Watcher. It makes sense that Dep is dependent on Watcher.

Post a snippet of the source code and get a feel for it:

export default class Dep { static target: ? Watcher; id: number; subs: Array<Watcher>; constructor () { this.id = uid++ this.subs = [] } addSub (sub: Watcher) { this.subs.push(sub) } removeSub (sub: Watcher) { remove(this.subs, sub) } depend () { if (Dep.target) { Dep.target.addDep(this) } } notify () { // stabilize the subscriber list first ... }Copy the code

Watcher

Paste source code snippets, feel one or two:

export default class Watcher { vm: Component; expression: string; cb: Function; id: number; deep: boolean; user: boolean; computed: boolean; sync: boolean; dirty: boolean; active: boolean; dep: Dep; deps: Array<Dep>; newDeps: Array<Dep>; depIds: SimpleSet; newDepIds: SimpleSet; before: ? Function; getter: Function; value: any; constructor ( vm: Component, expOrFn: string | Function, cb: Function, options? :? Object, isRenderWatcher? : boolean ) { this.vm = vm if (isRenderWatcher) { vm._watcher = this } vm._watchers.push(this) // options ... // parse expression for getter ... } get () { pushTarget(this) ... } addDep (dep: Dep) { const id = dep.id ... } cleanupDeps () { ... } / /... }Copy the code

Watcher will notify the update to re-render the view.

Common view update scenarios:

  1. Data changes – View changes that use data (corresponding: Render-watcher who urges view updates)
  2. Data change → computing properties that use data change → views that use computing properties change (corresponding: perform computed-watcher to urge updating of computing properties)
  3. (corresponding: user registered normal watcher (watch-API or watch property))

Component compilation

The idea of components is also the core of Vue, and compiling components into VDOM is also a difficult one!

You can find that there are many referenced figures in this section of Vue. In fact, some of them are similar, but more importantly, they have different focuses. Suggestions can be understood according to the flow chart, so as to achieve a comprehensive understanding.

component

Official examples:

// define a new component named button-counter Vue.component('button-counter', {data: function () {return {count: 0}}, template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>' }) <div id="components-demo"> <button-counter></button-counter> </div> new Vue({ el: '#components-demo' })Copy the code

Components also involve communication between components, slots, dynamic components, and so on. Follow up again watch (OS: this is what a big hole to dig oneself).

parse

The first step in the compilation process is to parse the template and generate the AST, which is an abstract syntax tree, a tree representation of the abstract syntax structure of the source code. Many compilation techniques, such as Babel, compile ES6 code as an AST. This process uses a lot of regular expression parsing for the string, and the source code is hard to read.

However, we need to know the four functions of start, end, comment and chars.

The processing process for common labels is as follows:

  1. Identify the start tag and generate the matching structure match.
  2. {name:’ XXX ‘,value:’ XXX ‘}
  3. Generate an astElement that handles the tags for,if, and once.
  4. Identify the closing tag and process elements that do not have a closing tag.
  5. Establish the parent-child relationship, and finally do all the Vue attribute related pair processing on astElement. Slot, Component, and so on.

Read: Vue Parse’s template to astElement source code

optimize

When our template goes through the parse process and outputs the AST tree, we need to optimize that tree.

The most important is markStaticRoots, markStatic nodes. If the nodes are static, the DOM they generate never needs to change, which makes updating the template even more interesting (unchanged nodes don’t need to be updated).

Question: Why does the child node element type static text add to the cost of the optimize process?

What is the cost of optimizing this static root node in the optimize process?

Objective: To reduce unnecessary comparison process and speed up update in patch process.

Cost: a. Storage objects of static templates need to be maintained. B. Multi-level render function calls.

Recommended reading

codegen

The final step of compilation is to convert the optimized AST tree into executable code, in the CodeGen section.

Main steps (call function) :

  1. generate
  2. genIf
  3. genFor
  4. genData & genChildren

This section is not much, just understanding. To learn more, see the source code.

Five, commonly used supplements

Keep -alive

Keepalive is a component built into Vue that allows included components to retain state or avoid rerendering. This is called component caching.

V-if, V-show, v-for

Three high-frequency subproblems:

  1. The difference between V-if and V-show?

A: V-if is equivalent to display. V-show = visibility; The former controls whether it is created, while the latter only controls whether it is hidden and displayed.

  1. Why can’t v-if and V-for be used together?

Answer: Because v-for has a higher priority than V-IF, the entire list will be traversed and then if will be used to determine whether to display, which consumes performance.

  1. Can we use index as the key in v-for?

A: Key is used for comparison in diff algorithm. Using index as key is not unique. When inserting an element, the key will also change. As a key, index is only applicable to list rendering output that does not depend on the child component state or temporary DOM state (e.g., form input values).

This melon does not do detailed answer here, want to know more, please solve by yourself.

Custom instruction

In Vue, Minxin, directive and filter have something in common. When registering, it is necessary to balance the advantages and disadvantages of local registration and global registration.

transition

In the process of reading the source code, I found that there is a large space in the source code describing the transition. In the official documentation, transition is also described as a separate and important section. Enter/Leave & List transitions, Vue Animations & Transitions, are easily overlooked points.

Six, the whole family bucket

Since using the Vue family bucket, my legs don’t hurt, my back doesn’t hurt either. Yi, a breath to write five pages, my mother no longer need to worry about my study. (Seems to be a bit of a string of ads……)

Vue-Router

The official route manager

There are two modes: Hash and History

  • Default hash mode by adding anchor points
  • History is implemented using the History. pushState API

Native: HTML5 introduces history.pushState() and history.replacestate () methods, which add and modify history entries, respectively. These methods are usually used in conjunction with window.onPopState. Details about the link

Vuex

Official Status Management

It consists of the following core parts:

  1. State: Data state;
  2. Mutations: To change a state;
  3. Getters: Filters a state in state and retrieves a new state;
  4. Actions: Performs multiple mutations, which can perform asynchronous operations (async);
  5. Modules: modules to classify states and management rules for a clearer directory structure;

VueCLI

Official scaffold

  • What is important in VueCLI4 is the configuration of the vue.config.js file.

VuePress

Static Website Generator

  • Using Vue + Webpack, you can use Vue components in Markdown, and the page is simple and generous, unified with the style of Vue official website.

NuxtJS

Server-side rendering

Seven, webpack

As long as you have two years or so of experience in front end, you’ll need to master a packing tool.

Webpack principle

Official explanation:

Webpack is a static module packaging tool for modern JavaScript applications. When WebPack works with an application, it builds a dependency graph internally that maps each module required by the project and generates one or more _bundle_.

Core concepts:

  1. Entry: The first step in Webpack’s execution of the build starts with an Entry, which can be abstracted into input.
  2. Everything in Webpack is a Module. A Module corresponds to a file. Webpack will recursively find all dependent modules from the configured Entry.
  3. Chunk: code block. A Chunk consists of multiple modules and is used for code merging and splitting.
  4. Loader: converts the original content of the module into the new content as required.
  5. Plugins: Extensions that listen for events that are broadcast at specific times in the Webpack build process and do something at specific times.

Function:

Code conversion, file optimization, code segmentation, module merge, automatic refresh, code verification, automatic publishing.

Optimize packing speed

  1. Install webpack-parallel-Uglify-plugin to speed up the process of “compress JS=> compile to AST=> restore JS”.
  2. Use HappyPack to improve the parsing speed of the Loader.
  3. Use the DLLPlugin and DLLReferencePlugin plugins, packaged in advance.
  4. Tree-shaking is used to eliminate useless modules.

AMD, CMD

Front-end modularity has four specifications: CommonJS, AMD, CMD, and ES6.

  1. AMD (Asynchronous module Definition)
  2. CMD (Generic module definition)
AMD (Asynchronous module Definition) CMD (Generic module definition)
Speed is fast Poor performance
It wastes resources Load dependencies only when they are truly needed
All dependencies are loaded in advance and are not executed until used Dependencies are not defined until they are used
  1. Node.js is a major practitioner of the commonJS specification: Module, module.exports (exports), require, global.

  2. ES6 implements module functions at the level of language standards, mainly consisting of two commands: export and import. The export command is used to specify the external interfaces of a module. The import command is used to enter the functions provided by other modules.

Q: How do import and require differ?

import require
Modular solutions in the ES6 standard Is a CommonJS compliant modular solution for Node
Dynamic import is not supported Support dynamic import
Is the key word Not a key word
Load at compile time and must be placed at the top of the module Runtime load, theoretically anywhere, right
With good performance Poor performance
Real-time binding, where import and export values point to the same memory location If the exported value changes, the imported value will not change
Executes as require/exports

More: Front-end modularity: CommonJS,AMD,CMD,ES6

Implement plugin (Tencent WXG test point)

  1. Create a plugins/demo-plugin.js file;
  2. Options;
  3. Writing files through Compilation;
  4. Manage Warnings and Errors

Implement a Webpack Plugin from zero

Four series:

What’s your favorite algorithm?

Actually Bengua wanted to answer: I like subtraction best! Because a happy life requires subtraction. 😄

This part of the algorithm is also a long time ago, since it can not escape, then face challenge it! It’s not that hard.

A picture is worth a thousand words

  • Original brain map, reproduced please explain the source

Series knowledge: data structure, basic algorithm, sorting algorithm, advanced algorithm.

Serial memory:

Algorithm ALGORITHM I’m not afraid to beat down data structure traversal sort my most slippery pointer dynamic greedy brush

1. Data structure

The queue

First in, first out.

The stack

First in, then out.

The heap

A heap is usually an array of objects that can be viewed as a tree.

The heap always satisfies the following properties:

  1. The value of a node in the heap is always no greater than or less than the value of its parent;
  2. The heap is always a perfect binary tree.
  • Complete Binary Tree: A Binary Tree in which all the layers are full except the last one, and the last one is either full or lacks consecutive nodes on the right, is a Complete Binary Tree — wiki.

(Ben melon had been tortured this point, big factory is the examination “data structure”, don’t escape, come out to mix sooner or later is to return 😭).

The list

  • Loop List (test site)
Function Node(element){this.element = element; this.prev = null; this.next = null; } function display(){ var current = this.head; // Exit the loop when the loop ends. (current.next == null) && ! (current.next.element=='head')){ print(current.next.element); current = current.next; } } function Llist(){ this.head = new Node('head'); this.head.next = this.head; this.find = find; this.insert = insert; this.display = display; this.findPrevious = findPrevious; this.remove = remove; }Copy the code

The hash

Hash function (English: Hash function) also known as Hash algorithm, Hash function. Store data in Key:Value mode.

The biggest characteristic of hash table is that it can locate the data to be searched quickly, and the time complexity of query is close to O(1). This melon suggests that you can put all the data structure here “add, delete, change and check” the time complexity of the operation, is also to be tested.

Time complexity, space complexity

Simple understanding:

  1. The number of loops is written in terms of n, which is the time complexity.
  2. The number of requested variables is expressed in terms of n, which is the space complexity.

The time complexity is more important. The common time complexity is O(1), O(n), O(logn), O(n2). If you don’t know how to calculate the interview/written test, just guess in this one. Really not answer: O(n) ~ O(n2) between, large probability will not be wrong 🐶.

Tree traversal (breadth, depth)

Breadth first Traversal (BFS) :

A Queue is used to store node objects. Queues are first in, first out. The sample

Depth first Traversal (DFS) :

  1. Preorder (root -> left subtree -> right subtree)
  2. Middle order (left subtree -> root -> right subtree)
  3. After order (left subtree -> right subtree -> root)

Second, the basic algorithm

Recursive thought

  • The famous Fibonacci sequence, you know!
function result(){
    if(n==1||n==2){
        return 1
    }
    return reslt(n-2)+result(n-1)
}
Copy the code
  • Function currying, you know!

Function currying: the technique of turning a function that takes multiple arguments into a function that takes a single argument (the first argument of the original function) and returns a new function that takes the remaining arguments and returns the result. – a wiki

Var add1 = function(a, b, c){return a + b + c; Var add2 = function(a) {return function(b) {return function(c) {return a + b + c; } } } // demo var foo = function(x) { return function(y) { return x + y } } foo(3)(4) // 7Copy the code

In this way, parameters can be appended directly instead of being written completely without the initial pass. This is just a brief talk, more please explore.

dichotomy

The request handwritten dichotomy, really not, can write down can also ah!

// Binary: First order, Function binary_search(arr,target) {let min=0 let Max =arr.length-1 while(min<= Max){let mid= math.ceil ((min+ Max)/2)  if(arr[mid]==target){ return mid }else if(arr[mid]>target){ max=mid-1 }else if(arr[mid]<target){ min=mid+1 } } return "Null"} the console. The log (binary_search (,5,7,19,88 [1], 19)) / / 3Copy the code

Three, sorting algorithm

Sorting is one of the more common and important ones, and not all of them are listed here. Only emphasize fast exhaust and bubble, can use double cycle.

Quick sort

Function quickSort(arr, I, j) {if(I < j) {let left = I; let right = j; let pivot = arr[left]; While (I < j) {while(arr[j] >= pivot && I < j) { } if(i < j) { arr[i++] = arr[j]; } while(arr[I] <= pivot && I < j) {// select * from (arr[I] <= pivot && I < j); } if(i < j) { arr[j--] = arr[i]; } } arr[i] = pivot; quickSort(arr, left, i-1); quickSort(arr, i+1, right); return arr; }}Copy the code

Bubble sort

Var arr=[10,20,50,100,40,200]; var arr=[10,20,50,100,40,200]; for(var i=0; i<arr.length-1; i++){ for(var j=0; j<arr.length-1-i; j++){ if(arr[j]>arr[j+1]){ var temp=arr[j] arr[j]=arr[j+1] arr[j+1]=temp } } } console.log(arr)Copy the code

Four, the advanced algorithm

Double pointer

You see “ordered” and “array.” Schedule the double pointer into your brain memory right now. Ordinary double pointer can not go, immediately want to collide pointer!

Example: Merging two ordered arrays (double pointer solution)

Example: input: nums1 =,2,3,0,0,0 [1], m = 3 nums2 = [6] 2, n = 3 output:,2,2,3,5,6 [1]Copy the code
/** * @param {number[]} nums1 * @param {number} m * @param {number[]} nums2 * @param {number} n * @return {void} Do not Return anything, modify nums1 in-place instead. */ const merge = function(nums1, m, nums2, n) {return anything, modify nums1 in-place instead. Let I = m - 1, j = n - 1, k = m + n - 1; while(I >= 0 && j >= 0) {// select * from (I >= 0 && j >= 0); If (nums1[I] >= nums2[j]) {nums1[k] = nums1[I] I -- k--} else {nums1[k] = nums2[j] j-- k--}} else {nums1[k] = nums2[j] j-- k--}} A special processing while (j > = 0) {nums1 [k] = nums2 [j], j, k}};Copy the code

Senior!

Dynamic programming

The idea of dynamic programming is to break a big problem down into smaller subproblems, and to be able to derive the solution of the original problem from the solutions of the smaller subproblems.

At the same time, the following two important properties must be satisfied to carry out dynamic programming:

  1. Optimal substructure
  2. Subproblem overlap property

Example of dynamic programming: Fibonacci sequence (mentioned above)

Fibonacci sequence: using recursion, although the code is very concise, but obviously with the increase of times, resulting in the growth of the recursion tree is very large, time-consuming.

Using dynamic programming to achieve the Fibonacci sequence, the code is as follows

Function feiBoLaQie(n) {// Create an array to hold Fibonacci array values. Let val = []; For (let I =0; let I =0; let I =0; i<=n; i++){ val[i] = 0; } if (n==1 || n==2){ return 1; } else{ val[1] = 1; val[2] = 2; for (let j =3; j<=n; j++){ val[j] = val[j-1] + val[j-2]; } } return val[n-1]; } console.log(feiBoLaQie(40)); / / 102334155Copy the code

By storing intermediate results in the array val, the if statement returns 1 if the Fibonacci number to be evaluated is 1 or 2. Otherwise, the values 1 and 2 will be stored at positions 1 and 2 in the val array.

The loop will iterate from 3 to the input parameter, assigning each element of the array to be the sum of the first two. At the end of the loop, the last element of the array will be the Fibonacci value that the function returns.

Dynamic programming is faster to solve.

  • Refer to the reading
  • More examples of dynamic programming

Greedy algorithm

The greedy algorithm follows an approximate problem solving technique, expecting to achieve global optimal (global optimal solution) by selecting local optimal (current best solution) at each stage.

Note: Getting greedy is an acceptable solution, not always an optimal solution.

Example: minimum coin change problem

It is to give the amount of change and the number of coins available and find out how many ways to get change. 1,5,10,25 what do we get for giving thirty-six cents?Copy the code
function MinCoinChange(coins){ var coins = coins; var cache = {}; this.makeChange = function(amount){ var change = [], total = 0; for(var i = coins.length; i >= 0; i--){ var coin = coins[i]; while(total + coin <= amount){ change.push(coin); total += coin; } } return change; } } var minCoinChange = new MinCoinChange([1, 5, 10, 25]); minCoinChange.makeChange(36); //[25, 10, 1] is a quarter, a dime, and a pennyCopy the code

Five series:

What do you know about Web security?

A picture is worth a thousand words

  • Original brain map, reproduced please explain the source

Cross-domain, XSS, CRFS, SQL injection, DNS hijacking, HTTP hijacking.

Tandem memory: three cross two hijack one injection

A, across the field

Cross domain definition

If the protocol, domain name, or port used to request a URL is different from the current page URL, it is cross-domain.

Cross-domain restriction is a protection mechanism of the browser. If cross-domain restriction is used, then:

  1. Cannot read cookies, LocalStorage, and IndexedDB for non-same web pages.
  2. You cannot touch the DOM of non-homologous web pages.
  3. Unable to send AJAX requests to non-same-origin addresses

Cross-domain solutions

Cross-domain solution:

  1. The json.
  2. CORS (cross-domain resource sharing);
// Common cross-domain request: just set access-control-allow-origin on the server side. // Cross-domain requests with cookies: both the front and back ends need to be set. / / such as the front set in axios axios. Defaults. The withCredentials = trueCopy the code
  1. Vue project set proxy proxy;
  2. Nginx proxy;
  3. Set document.domain to solve the problem of not being able to read the same source webpage Cookie;
  4. Cross-document communication API: window.postMessage();

Second, the XSS

XSS principle

The idea behind XSS is that WEB applications confuse user-submitted data with the code boundaries of JS scripts, causing browsers to execute user input as if it were JS code. XSS is targeted at ordinary users on the browser side.

Example:

<input type="text" value="<%= getParameter("keyword") %>"> <%= getParameter("keyword") %> </div>Copy the code

When the browser requests

http://xxx/search?keyword="><script>alert('XSS'); </script>Copy the code

Malicious code, it will execute

Reflective XSS

Attack steps of storage XSS:

  1. The attacker submits the malicious code to the target site’s database.
  2. When the user opens the target site, the server pulls the malicious code out of the database and returns it to the browser in HTML.
  3. The user’s browser receives the response, parses it and executes the malicious code mixed in.
  4. Malicious code steals user data and sends it to the attacker’s website, or impersonates a user to invoke the target website interface to perform operations specified by the attacker.

Such attacks are common on web features with user saved data, such as forum posts, product reviews, and private messages.

Type stored XSS

The attack steps of reflective XSS:

  1. Attackers construct special urls that contain malicious code.
  2. When a user opens a URL with malicious code, the web server takes the malicious code out of the URL and returns it to the browser in HTML.
  3. The user’s browser receives the response, parses it and executes the malicious code mixed in.
  4. Malicious code steals user data and sends it to the attacker’s website, or impersonates a user to invoke the target website interface to perform operations specified by the attacker.

The difference between reflected XSS and stored XSS is that the malicious code of stored XSS is stored in the database, while the malicious code of reflected XSS is stored in the URL.

The DOM model XSS

DOM XSS attack steps:

  1. Attackers construct special urls that contain malicious code.
  2. The user opens a URL with malicious code.
  3. The user’s browser receives the response, parses it and executes it. The front-end JavaScript pulls out the malicious code in the URL and executes it.
  4. Malicious code steals user data and sends it to the attacker’s website, or impersonates a user to invoke the target website interface to perform operations specified by the attacker.

DOM XSS is different from the previous two XSS: In DOM XSS attack, the extraction and execution of malicious code is done by the browser side, which is a security vulnerability of the front-end JavaScript itself, while the other two XSS are security vulnerabilities of the server side.

XSS defenses

  1. Input filtering, do not trust any client input;
  2. Fully escape the HTML;
  3. Http-only: JavaScript is not allowed to read some sensitive cookies. An attacker cannot steal this Cookie even after XSS injection is complete.
  4. Verification code: prevents scripts from posing as users to submit dangerous operations.
  5. Use with caution:.innerhtml,.outerhtml, document.write();

Third, CSRF

CSRF principle

Cross-site request forgery: An attacker induces a victim to visit a third-party website, and then sends a cross-site request to the attacked website. The registration certificate obtained by the victim from the attacked website is used to bypass the user authentication in the background and to impersonate a user to perform an operation on the attacked website.

CSRF was used in the famous Google Email theft in 2009.

Main process:

  1. The victim logged on to a.com and retained the login credentials (cookies).
  2. The attacker lured the victim to b.com.
  3. B.com sent a request to a.com: a.com/act=xx. The browser will carry a.com cookies by default.
  4. After receiving the request, A.com verified the request and confirmed that it was the victim’s credentials, mistaking it for the victim herself.
  5. A.com was executed on behalf of the victims.
  6. The attack was complete, and the attacker impersonated the victim and had the a.com perform its own defined operation without the victim’s knowledge.

Note: Attackers cannot directly steal users’ information (cookies, headers, website content, etc.), but only fraudulently use the information in cookies.

This tells us that you can’t just click on links while surfing, it’s risky.

CSRF defense

Defense strategy:

  1. Automatic defense policy: Origin detection (Origin and Referer authentication).
  2. Active defense measures: Token authentication or double Cookie authentication and Samesite Cookie.
  3. Ensure that pages are idempotent, and that back-end interfaces do not perform user operations in GET pages.

Iv. SQL injection

SQL Injection Principles

Sql injection is an attack by inserting malicious Sql queries or adding statements into the input parameters of the application, and then parsing and executing on the Sql server in the background. It is one of the most commonly used methods for hackers to attack databases at present.

SQL Injection Defense

Defense: Precompiling and binding variables with SQL statements is the best way to defend against SQL injection. You can also defend against this by rigorously checking the data types of the parameters.

DNS hijacking

Principles of DNS hijacking

DNS hijacking, also known as domain name hijacking, refers to the interception of domain name resolution requests within the scope of the hijacked network, analyze the requested domain name, and release the requests outside the scope of the review. Otherwise, a false IP address is returned or nothing is done to make the request lose response. Its effect is that the specific network cannot be accessed or the access is a fake URL. In fact, the essence of DNS resolution server tampering

DNS Hijacking Defense

The solution:

The hijacking process of DNS is achieved by attacking the carrier’s resolution server. We can use our own resolution server instead of the carrier’s DNS resolution or send the resolved domain name in the form of IP in our App in advance to bypass the carrier’s DNS resolution, so as to avoid the problem of DNS hijacking.

HTTP hijacking

How HTTP hijacking works

Protocol detection is configured on the carrier’s router node. If the request is found to be AN HTTP request or an HTML request, it is intercepted and maliciously processed.

There are two common types:

  1. Similar to DNS hijacking returns 302 to redirect the user’s browser to another address. (This is what phishing sites do)
  2. Inserts JS or DOM nodes (advertisements) into the HTML data returned by the server. (common)

HTTP hijacking Defense

Defense:

  1. Using HTTPS;
  2. Use a transcoding declaration;
  3. In the development of the web page to add code filtering: with JS check whether all outside the chain belongs to the whitelist;
  4. Contact the carrier;

This part is more of a conceptual thing. I don’t want to remember it completely, but I should be able to say something about it. As the old saying goes, “You know what you know, you don’t know what you don’t know. The interviewer is not strict with you on non-critical questions. Don’t be full of gossip or say you don’t know.

summary

Obviously, the front interview “series” questions are not limited to the above, this melon will continue in accordance with the “series association” thinking to sort out, constantly to break the system, the formation of the system (dig their own sinkhole). Look forward to finding traces of truth in this repeated process!