Javascript based

0.1 + 0.2 === 0.3?

The bottom layer of a computer is represented by binary, and for numbers like 0.1 and 0.2, there will be accuracy errors when stored in binary

Base64 encoding principle

The binary data is grouped in groups of 6 bits, and each group is preceded by two high 0s. Then the 8-bit bytes are converted into decimal, and the corresponding encoded characters are obtained according to the BASE64 encoding table. A byte is 8bit, a base64 character is 6bit, 24 is the least common multiple, so three bytes can be completely converted into four base64 characters; But we can’t control that the data we need to encode is exactly multiples of 3, so we do zeroing – padding 0x00 at the end of strings that are less than multiples of 3; Because the subscript 0 in the base64 encoding corresponds to A character ‘A’, and the 0x00 on the trailing padding is also the subscript 0x00 after grouping zeros, it is impossible to tell whether it is the trailing padding 0x00 or the 0x00 in binary data. So the equal sign was introduced, which is why the ‘=’ character is not in the Base64 character set, but also in the Base64 encoding.

The base64 encoding steps for 6666P show that each character is converted to 8bit: 6 -- -- -- -- - > 00110110 - > 00110110 6 -- -- -- -- - > 00110110 - > 00110110 P -- -- -- -- - > 01010000 to fill a -- -- -- -- - > 00000000 whole stitching results: 001101100011011000110110001101100101000000000000 - bit with 6 a set of segmentation: 001101 100011 011000 110110 001101 100101 000000 000000 convert to Base64 encoding pins: 13 35 24 54 13 37 00 Obtain the corresponding Base64 encoding pins: String (8) "NjY2NlA="Copy the code

this

var length = 10; function fn() { console.log(this.length); } var obj = { length: 5, method: function(fn) { fn(); arguments[0](); }}; obj.method(fn, 1);Copy the code

The output

10
2
Copy the code

Variable ascension

When a function runs, it first creates the execution context, then pushes the execution context onto the stack, and then runs the execution context when the execution context is at the top of the stack. Three things are done during the creation of an execution context: Function (arguments); function (arguments); function (arguments); function (arguments); It then scans the var variable declaration and creates a property of the same name with the value undefined, which is called variable promotion. Let has variable promotion, but different from var, var’s variable promotion will be assigned with undefined by default. The let is only promoted and does not assign any value to the variable. Any reading or writing of the variable before explicit assignment will result in ReferenceError. The area between the start of a code block and the evaluation (including assignment) of a variable is called the temporary dead zone for that variable.

Question 1

var x = 21;
var girl = function () {
    console.log(x);
    var x = 20;
};
girl ();
Copy the code

The output

undefined
Copy the code

Question 2

(function () { try { throw new Error(); } catch (x) { var x = 1, y = 2; console.log(x); } console.log(x); console.log(y); }) ();Copy the code

The output

1
undefined
2
Copy the code

How does the event loop /JS execution /JS implement asynchrony

First, JavaScript is single-threaded, and for good reason with limited resources, there are synchronous and asynchronous tasks. An event loop is a process in which tasks in the event queue are placed on the thread to be executed and the process is repeated.

We divide the task area into micro tasks and macro tasks:

Macro-task: includes the entire code script, setTimeout, and setInterval

Micro-task: Promise, process.nexttick

setTimeout(function() {
    console.log('setTimeout');
})

new Promise(function(resolve) {
    console.log('promise');
}).then(function() {
    console.log('then');
})

console.log('console');
Copy the code

This code enters the main thread as a macro task. When a setTimeout is encountered, its callback function is registered and distributed to the macro task Event Queue. (The registration process is the same as above, not described below.) A Promise is then encountered, the new Promise is immediately executed, and the then function is dispatched to the microtask Event Queue. If console.log() is encountered, execute immediately. Ok, the whole script is executed as the first macro task. What are the microtasks? We found that then is executed in the microtask Event Queue. Ok, the first round of the Event loop is over, so let’s start the second round, starting, of course, with the macro task Event Queue. We find the callback function corresponding to setTimeout in the macro task Event Queue and execute it immediately. The end.

ES6 Static keyword

Add methods directly to the function objects of the class, rather than putting them on the prototype chain

The difference between an arrow function and a normal function

  1. Arrow functions cannot be used as constructors without constructor
  2. The arrow function is declared as this and is not affected by bind, call, or apply

JS data type

Number String Boolean Object Function Array Symbol Null Undefined BigInt

NaN

Not a number

NaN ! == NaN typeof NaN === 'number' Boolean(NaN) === falseCopy the code

Determine type

  1. Typeof can only distinguish object and function for objects; typeof null === ‘object’
  2. Instanceof is often used to determine a specific object type

Instanceof can only determine the type of object

1 instanceof Number === false
'1' instanceof String === false
Copy the code

However, you can also specify how an instance of an object is judged

class CheckIsNumber {
  static [Symbol.hasInstance](number) {
    return typeof number === 'number'
  }
}

// true
1 instanceof CheckIsNumber
Copy the code
  1. Object. The prototype. ToString. Call to determine the type of the most perfect, seems to be the best way
  2. isXXX Api Array.isArray isNaN

Type conversion

Casts.

Number()
Boolean()
String()
toString()
Copy the code
  1. Rules for transferring booleans

Undefined, null, false, NaN, ”, 0, -0 all return false, others return true 2. False, null = 0, true = 1, undefined and unconvertible string NaN, symbol error, string if numeric and binary normal conversion

Implicit conversion

  1. Object to basic type
    • Call Symbol. ToPrimitive and the transition is complete
    • Call valueOf, and the conversion is successful
    • Call toString and end on success
    • An error
  2. arithmetic
    • Only when one side of an addition is a string will the other be converted to a string
    • As long as one of the other operations is a number, the other becomes a number
  3. = =The operator
[] = =! [] //trueCopy the code

x == y

  • If x and y belong to the same data type

The reason for page stutter

  1. If too many network requests cause slow data return, you can perform some caching or request merging
  2. If the bundle of a resource is too large, you can split it
  3. Js code, is there too many loops somewhere that cause the main thread to take too long
  4. The browser rendered too many things in one frame, causing a lag
  5. Rearrange redraw is triggered frequently during page rendering
  6. A memory leak

Garbage collection mechanism

  1. Variables in the global state (window) are not automatically reclaimed
  2. Mark-clear. After leaving a local scope, variables in that scope that are not referenced by an external scope are marked and then cleared
  3. Mark-collation: After clearing some garbage data and releasing certain memory space, a large area of discontinuous memory fragments may be left. As a result, continuous memory may not be allocated for some objects in the future. In this case, memory space needs to be collated
  4. Because JavaScript runs on the main thread, js will be suspended when garbage collection mechanism is implemented. If garbage collection takes too long, it will bring obvious lag phenomenon to users. Therefore, garbage collection mechanism will be divided into small tasks interspersed with JS tasks, namely, alternate execution. As much as possible, make sure that there is no obvious lag

A memory leak

Memory that is no longer used was not freed due to negligence or some program error.

  1. Improper use of closures causes memory leaks
  2. The global variable
  3. Detached DOM nodes: Suppose you remove a DOM node manually. You should have freed the memory occupied by the DOM node, but inadvertently some code still refers to the removed node, so that the memory occupied by the node cannot be freed
    let btn = document.querySelector('button')
    let child = document.querySelector('.child')
    let root = document.querySelector('#root')
    
    btn.addEventListener('click', function() {
        root.removeChild(child)
    })
    Copy the code
  4. Console printing: If the browser doesn’t always keep information about the objects we print, why do we see concrete data every time we open the Console of the control
  5. Timer for forgetting
    function fn1() {
        let largeObj = new Array(100000)
    
        setInterval(() => {
            let myObj = largeObj
        }, 1000)
    }
    Copy the code

Javascript written questions

Fibonacci numbers

function getFibonacci(n) {
  let fibonacci = [];
  let i = 0;
  while (i < n) {
    if (i <= 1) {
      fibonacci.push(i)
    } else {
      fibonacci.push(fibonacci[i - 1] + fibonacci[i - 2]);
    }
    i++
  }
  return fibonacci
}
Copy the code

palindrome

str === str.split('').reverse().join('')
Copy the code

Currie,

  1. Execute only when the number of parameters is sufficient
function createCurry(func, args) {
  var originArgsLen = func.length;
  var args = args || [];
  
  return function () {
    var _args = [].slice.apply(arguments);
    args.push(..._args);
    
    if (args.length < originArgsLen) {
      return createCurry.call(this, func, args);
    }
    
    return func.apply(this, args);
  }
}
Copy the code
  1. Execute by passing in arguments

new

  1. Create an empty object
  2. Gets the constructor, the first argument
  3. Link the constructor’s prototype to the instance’s __proto__
  4. Execute the constructor as this with the remaining parameters and the current instance
  5. An object is returned if the constructor returns the object, an instance is returned otherwise
function myNew() {
    let obj = {};
    let constructor = [].shift.call(arguments);
    obj.__proto__ = constructor.prototype;
    const result = constructor.apply(obj, arguments);
    if(result && typeof result === 'object') return result;
    return obj;
}
Copy the code

Promise

class MyPromise { constructor(fn) { this.callbacks = []; this.state = "PENDING"; this.value = null; fn(this._resolve.bind(this), this._reject.bind(this)); } then(onFulfilled, onRejected) { return new MyPromise((resolve, reject) => this._handle({ onFulfilled: onFulfilled || null, onRejected: onRejected || null, resolve, reject, }) ); } catch(onRejected) { return this.then(null, onRejected); } _handle(callback) { if (this.state === "PENDING") { this.callbacks.push(callback); return; } let cb = this.state === "FULFILLED" ? callback.onFulfilled : callback.onRejected; if (! cb) { cb = this.state === "FULFILLED" ? callback.resolve : callback.reject; cb(this.value); return; } let ret; try { ret = cb(this.value); cb = this.state === "FULFILLED" ? callback.resolve : callback.reject; } catch (error) { ret = error; cb = callback.reject; } finally { cb(ret); } } _resolve(value) { if (value && (typeof value === "object" || typeof value === "function")) { let then = value.then; if (typeof then === "function") { then.call(value, this._resolve.bind(this), this._reject.bind(this)); return; } } this.state === "FULFILLED"; this.value = value; this.callbacks.forEach((fn) => this._handle(fn)); } _reject(error) { this.state === "REJECTED"; this.value = error; this.callbacks.forEach((fn) => this._handle(fn)); } } const p1 = new Promise(function (resolve, reject) { setTimeout(() => reject(new Error("fail")), 3000); }); const p2 = new Promise(function (resolve, reject) { setTimeout(() => resolve(p1), 1000); }); p2.then((result) => console.log(result)).catch((error) => console.log(error));Copy the code

call

Function.prototype.myCall = function() { const context = [].shift.call(arguments) || windows; context.fn = this; context.fn(... arguments); delete context.fn }Copy the code

bind

Function.prototype.myBind = function() { const context = [].shift.call(arguments) || windows; const _this = this; const args = arguments return function() { _this.call(context, ... args, ... arguments) } }Copy the code

apply

Function.prototype.myApply = function() { const context = [].shift.call(arguments) || windows; context.fn = this; context.fn(... arguments[0]); delete context.fn }Copy the code

copy

Shallow copy

const a = {... b} const a = Object.assign({}, b)Copy the code

Deep copy

function deepCopy(obj) {
    let copy = obj instanceof Array ? [] : {};
    for(let i in obj) {
        if(obj.hasOwnProperty(i)) {
            if(typeof obj[i] === 'object') {
                copy[i] = deepCopy(obj[i]);
            } else {
                copy[i] = obj[i]
            }
        }
    }
    return copy;
}
Copy the code

debounce

A function is executed if it does not fire a second time at a specified time

function debounce(fn, time) { let timer = null; return function() { const args = [...arguments]; timer && clearTimeout(timer); timer = setTimeout(() => { fn(... args) }, time) } }Copy the code

throttle

A function can fire only once in a specified period of time

function throttle(fn, time) { let timer = null; let lastTriggerTime = Date.now(); return function() { const span = Date.now() - lastTriggerTime; if(span >=time) { fn(... arguments) } } }Copy the code

instanceof

function instanceOf(left, right) {
    let leftProto = left.__proto__;
    let rightPrototype = right.prototype;
    while(true) {
        if(leftProto === null) {
            return false;
        }
        if(leftProto === rightPrototype) return true
        leftProto = leftProto.__proto__
    }
}
Copy the code

Array to heavy

Array. The from (new Set (,2,3,3 [1]))Copy the code

Array flattening

function flatArray(arr) {
    let result = [];
    arr.forEach(item => {
        if(Array.isArray(item)) {
            result = result.concat(flatArray(item))
        } else {
            result = result.concat(item)
        }
    })
    return result;
}

Copy the code

String parsing — CSV

The target

  1. '1,2,3'= >[[' 1 ', '2', '3']]
  2. 'a, b, "c, d"= >[['a', 'b', 'c, d']]
  3. '" he said, "I' ll stay, here" "", 2, 3, ABC = -.," ABC ", "" "" \ n4 interchange, 5, "" '= >[['he,said"I'll, stay, here"', '2', '3', 'abc=-.', 'abc', '"'], ['4', '5', '']]
function parse(csv) { if(! csv) return const rows = csv.split('\n'); return rows.map(row => row.trim().split(",(? = ([^ \ \ \ \ \ \ ""] * [^ \ \ \ \ \ \" "] *) * [^ \ \ \ "] * $) ", 1)) }Copy the code

String parsing – URL Params as object

The input

let url = 'http://www.domain.com/?user=anonymous&id=123&id=456&city=%E5%8C%97%E4%BA%AC&enabled';
Copy the code

The output

{user: 'anonymous', id: [123, 456], // The duplicate key is assembled into an array, and the number that can be converted into a number is converted into a number. True, // The value key convention is not specified to be true} */Copy the code

methods

function parseParam(url) { const paramsStr = /.+\? (.+)$/.exec(url)[1]; const paramsArr = paramsStr.split('&'); let paramsObj = {}; paramsArr.forEach(param => { if (/=/.test(param)) { let [key, val] = param.split('='); val = decodeURIComponent(val); val = /^\d+$/.test(val) ? parseFloat(val) : val; if (paramsObj.hasOwnProperty(key)) { paramsObj[key] = [].concat(paramsObj[key], val); } else { paramsObj[key] = val; } } else { paramsObj[param] = true; } }) return paramsObj; }Copy the code

String parsing – Template engine implementation

The input

Let template = 'I am {{name}}, age {{age}}, gender {{sex}}'; Let data = {name: 'name ', age: 18}Copy the code

The output

I’m name, age 18, gender

methods

function render(template, data) {
  const reg = /\{\{(\w+)\}\}/;
  if (reg.test(template)) {
    const name = reg.exec(template)[1];
    template = template.replace(reg, data[name]);
    return render(template, data);
  }
  return template;
}
Copy the code

String conversion – hump naming

The input

var s1 = "get-element-by-id"
Copy the code

The output

getElementById

methods

var f = function(s) { return s.replace(/-\w/g, function(x) { return x.slice(1).toUpperCase(); })}Copy the code

The maximum number of characters in a string

The input

"abcabcabcbbccccc"
Copy the code

The output

c 8

methods

let num = 0; let char = ''; str = str.split('').sort().join(''); let re = /(\w)\1+/g; str.replace(re,($0,$1) => { if(num < $0.length){ num = $0.length; char = $1; }})Copy the code

String conversion – thousands separator

The target

12345.78 => 12,345.78

123456890 = > 123456890

The replace() method of the string stringObject performs a look-and-replace operation. It looks in stringObject for the substrings that match regexp, and then replaces them with replacement. If regexp has the global flag G, the replace() method replaces all matching substrings. Otherwise, it replaces only the first matching substring.

function parseToMoney(num) { num = parseFloat(num.toFixed(3)); let [integer, decimal] = String.prototype.split.call(num, '.'); integer = integer.replace(/\d(? =(\d{3})+$)/g, '$&,'); return integer + '.' + (decimal ? decimal : ''); }Copy the code

String conversion – swap names

The input

Sue, Zhao

The output

Zhao Sue

methods

str.replace(/(\s*\w+\s*), (\s*\w+\s*)/, '$2 $1')
Copy the code

html

datalist

The datalist property in H5 provides auto-completion for text entry boxes

<input type="search" maxLength ="32" placeholder=" search" value="" class="search-input" data-v-1a3f6ED6 ="" list="search"> <datalist id="search"> <option value="123"></option> <option value="456"></option> </datalist>Copy the code

CSS

Range of new features

border-radius box-shadow rgba text-shadow gradien ::selection transform border-image column-count/rule/gap

link import

  1. Link is an HTML tag with no compatibility problems. Import is incompatible with IE5-
  2. Link page is loaded at the same time. Load the import page after it has loaded
  3. Link can be dynamically introduced with JS; The import does not support
  4. Link introduces styles with a higher priority than import

The difference between inline and block-level elements

Block level elements always occupy a single line. You can set width, height, padding, and margin inline elements without newlines. You cannot set width and height, and you cannot set margin-bottom margin-top margin-bottom

The elves figure

Combine a bunch of small images into one large image. Then use CSS background-position combination for background positioning advantages:

  1. Reduce network requests
  2. Reduce image size
  3. Easy to change style
  4. Avoid naming problems

Disadvantage:

  1. Difficulty of locating pictures
  2. Maintenance trouble, a few background changes may affect the whole picture

Margin and padding use the scene

margin

  1. You need to add a spacing outside the border
  2. No background is required at the interval
  3. The spacing of the two boxes that are connected above and below needs to cancel each other out

padding

  1. The interval needs to be added inside the border
  2. Background is required at intervals
  3. The spacing of the two boxes connected above and below cannot cancel each other out

By Coderfei Link: juejin.cn/post/684490… The copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.

Is the vertical percentage of the element set relative to the height of the container

When setting the width of an element as a percentage, it is calculated relative to the width of the parent container. However, for attributes that represent vertical distance, such as padding-top, padding-bottom, margin-top, margin-bottom, etc., When they are set as percentages, they are also based on the width of the parent container, not the height.

The difference between CSS pseudo-classes and pseudo-elements

Hover active focus pseudo-element :before :after :first-letter :first-line virtual element

Hidden elements

  1. display: none
  2. visibility: hidden
  3. width: 0; height: 0;
  4. opacity: 0
  5. z-index: -1000

Remove the floating

What is floating

Remember that in CSS, some elements are block-level elements that automatically enable a new line, and there is another type of inline element, the inline element, that stays on the “line” with the previous content; However, sometimes we need to change this layout and use CSS floats to achieve this. CSS floats allow a given element to move to one side of its row, and other content to flow down. A right floating element will be pushed to the right of its container and content will flow down its left, while a floating element will be moved to the left and content will flow down its right. When an element is floated, it does not affect the layout of block-level elements, only the layout of inline elements.

Why clear the float

  1. The content overlap
  2. The parent container is highly collapsed

How to clear the float

Outer spacing fold

In CSS, the vertical margins of two or more adjacent boxes in a normal stream (which may be parent or sibling elements) are superimposed. The resulting margins are called margin superimposed.

  1. When two adjacent margins are both positive, the result of folding is the larger value between them.
  2. When two adjacent margins are both negative, the result of folding is the greater value of their absolute values.
  3. When two margins are positive and negative, the result of folding is the sum of the two.

Rgba opacity difference

Opacity is a CSS property that can be inherited; Rgba is an attribute value and will not be inherited

Eliminate newline Spaces between display: inline-block elements

A line break is placed between inline-block elements displayed in the same line, usually occupying 4px space (for example, the default size of a Chrome font is 16px, and the space between inline block elements is 4px, the larger the font size, the larger the space).

  1. The parent element font size is set to 0, reset from the element font.
  2. Remove or comment line breaks
  3. Letter – spacing indentation

Column layout

Column-count: indicates the number of columns. Column-gap: indicates the gap between each column. Column-rule: indicates the width of the dividing line between two columns

Horizontally and vertically centered background

background-position: center

Difference of Oblique ITALic

The former is slanted and the latter is italic. Oblique tilts a font without an italic attribute, and if it has an italic attribute, it is italic.

HTTP

TCP/IP five-tier model

Physical layer Link layer MAC Network layer IP ARP transport layer TCP UDP application layer HTTP FTP

HTTPS & HTTP

The full name of HTTPS is Hypertext Transfer Protocol Secure. From its name, we can see that HTTPS is more Secure than HTTPS. In fact, HTTPS is not a new application-layer Protocol. It is a combination of HTTP + TLS/SSL, and security is what TLS/SSL does.

  1. The access methods are different: one is an HTTPS prefix and the other is an HTTP prefix
  2. The default port number is different. HTTP default port 80 HTTPS default port 443
  3. HTTP is a protocol without secure encryption. Its transmission process is easy to be monitored by attackers, data is easy to be stolen, and sender and receiver are easy to be forged. HTTPS is a secure protocol, which can solve these problems through key exchange algorithm – signature algorithm – symmetric encryption algorithm – digest algorithm.

GET & POST

  1. The GET method is used to request resources, and the POST method is used to submit forms to modify resources
  2. The request parameters of the GET method are directly exposed in the URL and are vulnerable to forgery attacks. The request parameters of the POST method are invisible to the user in the request body
  3. The GET method has a length limit for the URL, and the BODY of the POST request has no length limit
  4. The browser defaults to cache GET requests
  5. For get requests, the browser sends both HTTP headers and data, and the server responds with 200 (return data). For POST, the browser sends a header, the server responds with 100 continue, the browser sends data, and the server responds with 200 OK.

Stateless protocol

HTTP is a stateless protocol, that is, how can a server become stateful when it does not retain any state in a transaction with a client

Cookie

The Cookie notifies the client to save the Cookie according to the set-cookie header field in the response packet sent from the server. When the client sends a request to the server next time, the client automatically adds the Cookie value to the request packet and sends the request packet.

That is, cookies are generated by the server, but sent to the client, and saved by the client. Cookies are added to each request. After discovering the Cookie sent by the client, the server will check which client sent the connection request, and then compare the records on the server to obtain the previous status information.

Session

Session is another mechanism for recording the client’s state, except that cookies are stored in the client browser, while sessions are stored on the server.

When the client browser accesses the server, the server records the client information on the server in a form called a Session. When the client browser visits again, all it needs to do is look up the client’s status from the Session.

Although the Session is held on the server and transparent to the client, it still requires the client’s browser to function properly. This is because a Session needs to use a Cookie as an identifier. The HTTP protocol is stateless and the Session cannot be identified as the same client based on the HTTP connection. Therefore, the server sends a Cookie named JSESSIONID to the client browser. Its value is the Session ID (that is, the set-cookie placed in the HTTP response header). The Session uses this Cookie to identify whether the user is the same. If the Cookie mechanism determines the identity of a customer by checking the “pass” on the customer, the Session mechanism determines the identity of the customer by checking the “customer list” on the server. A Session is a client file created by the program on the server. When a client visits the server, it only needs to query the client file table.

The difference between

  1. Cookie data is stored in the client’s browser, Session data is stored on the server, expiration or not determined by the server.
  2. Cookies are not very secure. Others can analyze cookies stored locally and cheat cookies. For security, Session should be used.
  3. Sessions are stored on the server for a certain amount of time. When the number of visits increases, it takes a lot of performance out of your server. Cookies should be used to alleviate server performance;
  4. The limit of a single Cookie on the client is 3K, that is to say, a site can not store more than 3K cookies on the client;
  5. Cookie and Session schemes belong to the client and server respectively, but the Session implementation of the server is dependent on the Cookie of the client. As I mentioned above, the Session ID value will be generated when the server implements the Session mechanism. This ID value will be sent to the client, the client will put this ID value in the HTTP request header to send to the server, and this ID value will be saved in the client, the container is the Cookie, so when we completely disable browser cookies, The Session on the server is also unavailable.
  6. Session: The session mechanism is a server-side mechanism that uses a hash table (and possibly a hash table) structure to hold information.

Cookies session mechanism: Cookies are small pieces of text that the server stores on the local computer and sends to the same server with each request. The Web server sends cookies to the client using HTTP headers. At the client end, the browser parses the cookies and saves them as a local file, which automatically binds any requests from the same server to these cookies

UDP & TCP

UDP stands for User Datagram Protocol. It speeds up communication by eliminating the need for a so-called handshake operation, allowing other hosts on the network to transfer data before the receiver agrees to communicate. TCP stands for Transmission Control Protocol. It helps you determine whether your computer is connected to the Internet and the data transfer between them. A TCP connection is established through a three-way handshake, which is used to initiate and confirm a TCP connection. Once the connection is established, data can be sent, and when the data transfer is complete, the connection is disconnected by shutting down the virtual circuit.

TCP UDP
Transmission is available only after a connection is established Transfer without connection
There is an order between packets There is no sequence between packets
The slower fast
Error checking + error fixing Error checking + direct discard
Header 20 bytes Header 8 bytes
TCP three-way handshake
  1. The client sends SYN (synchronization sequenceNumber) sequenceNumber = x
  2. 6. Some initials (g genumber = x + 1)
  3. 6. Some initials genumber = y + 1

Why not two handshakes?

In the case of two handshakes, the client knows that the server can send and receive packets, but the server only knows that the client can send packets, but does not know whether the client can receive packets

TCP quad handshake (terminate connection)

  1. The client sends the FIN and enters the FIN_WAIT_1 phase
  2. The server confirms and sends an ACK. The client receives the ACK and enters the FIN_WAIT_2 phase
  3. The server sends the FIN and the client enters the TIME_WAIT phase
  4. Clients in TIME_WAIT state are allowed to re-send ACKS to the server to prevent information loss. The amount of time a client spends in TIME_WAIT depends on its implementation, and after waiting some time, the connection is closed and all resources (including port numbers and buffer data) on the client are released.

HTTP Code

1XX

Used for informational prompt

  1. 100 Continue The original request has been accepted and the customer should Continue to send the rest of the request
  2. The 101 Switching Protocols server understands and is willing to comply with client requests containing the Upgrade header field to change the application layer protocol used for the current connection.

2XX

successful

  1. 200 All is well
  2. The 201 Created request succeeds, the server creates a new resource, and the Location header gives its URL
  3. 202 Accepted request successful, but server not processed (done)
  4. The Authoritative Information document has returned normally, but some of the reply headers may be incorrect because a copy of the document is used, not Authoritative Information
  5. 204 No Content The server handled the request correctly but did not return any Content (the document is not updated and does not need to return)
  6. 205 Reset Content There is no new Content, the browser should force clear form entries
  7. 206 Partial Content The Partial Content server completed a request with a Range header sent by the client

3XX

Redirect, the client browser must do more to fulfill the request

  1. The document requested by the 300 Multiple Choices customer can be found in Multiple locations that are already listed in the returned document. If the server wants to propose a preference, it should be indicated in the Location reply header.
  2. 301 Moved Permanently The document requested by the Permanently customer is elsewhere, the new URL is given in the Location header, and the browser should automatically access the new URL
  3. 302 Found is similar to 301, but the new URL should be considered a temporary replacement, not permanent. When this status code appears, the browser is able to access the new URL automatically.
  4. 303 See Other is similar to 301/302, except that if the original request was POST, the redirected target document specified in the Location header should be extracted via GET
  5. 304 Not Modified The client has a cached document and makes a conditional request (typically providing an if-Modified-since header indicating that the client only wants to update the document after the specified date)
  6. The document requested by the customer should be retrieved through the Proxy server specified in the Location header
  7. 307 Temporary Redirect Similar to 303 but the browser can only follow redirects to GET requests

4XX

Client error

  1. 400 Bad Request syntax error
  2. 401 Unauthorized Access Was denied. A customer attempted to gain Unauthorized access to a password-protected page
  3. 403 Forbidden The resource is unavailable. The server understands the client’s request, but refuses to process it
  4. 404 Not Found The resource at the specified location could Not be Found. This is also a common response
  5. 405 Method Not Allowed Request methods such as GET, POST, HEAD, DELETE, PUT, and TRACE do Not apply to the specified resource
  6. 406 Not Acceptable The resource specified has been found, but its MIME type is Not compatible with that specified by the customer in the Accpet header
  7. 407 Proxy Authentication Required Requires Proxy Authentication. Similar to 401, the customer must first be authorized by the Proxy server
  8. 408 Request Timeout The client does not send any Request within the waiting time permitted by the server
  9. 409 Conflict is usually associated with PUT requests. The request cannot succeed because it conflicts with the current state of the resource
  10. The document requested by 410 Gone is no longer available, and the server does not know which address to redirect to
  11. 411 Length Required The content-Length header is missing.
  12. Some preconditions specified in the request header Failed
  13. 413 Request Entity Too Large The size of the target document is larger than the server is currently willing to process. If the server thinks it can process the request later, it should provide a retry-after header
  14. 414 Request URI Too Long The URI is Too Long
  15. 415 Unsupported MIME types
  16. 416 Requested Range Not Satisfiable server cannot satisfy the Range header specified in the request.

5XX

  1. 500 Internal Server Error The Server encountered an unexpected situation and could not complete the customer’s request
  2. 501 Not Implemented Server does Not have the function to complete requests. For example, the server may return this code if it does not recognize the request method
  3. 502 Bad Gateway The server, acting as a Gateway or proxy, receives an invalid response from the upstream server
  4. 503 Service Unavailable The Service is Unavailable. The server fails to respond due to maintenance or heavy load
  5. 504 Gateway Timeout Indicates the Gateway Timeout. This parameter is used by the server acting as a proxy or Gateway. It indicates that the remote server cannot receive a response in a timely manner
  6. 505 HTTP Version Not Supported The server does Not support the HTTP Version specified in the request

HTTP cache

Blog.csdn.net/u012375924/… www.cnblogs.com/ranyonsue/p… Blog.csdn.net/ws9029/arti…

The cache control

The switch that controls caching, which identifies whether caching is enabled and which caching mode is used for requests or access

  1. Pragma & Expires The Pragma sets a time for no-cache to disable cache Expires
  2. Cache-Control

Cache invalidation

How do I validate the cache, for example, how do I define the expiration date of the cache, and how do I make sure the cache is up to date

The HTTP request header

General header

Cache-Control

  1. As a request header

  2. As a response header

Pragma

Connection

  1. Keep-alive Does not close the network connection after a transaction is completed
  2. Close Close the network connection after a transaction is complete

Entity header

Content-Length

The size, in bytes, of the entity body sent to the receiver

Content-Language

A language that is acceptable to the client or server

Content-Encoding

This entity header is used to compress the media type. Content-encoding indicates what Encoding is applied to the entity. Common content encodings include gzip, COMPRESS, Deflate, and Identity. This attribute can be applied to request packets and response packets

Content-Type

The media type of the entity body

Address bar Enter URL to page display

DNS Domain name Resolution

  1. Browser cache
  2. System cache
  3. Router cache
  4. Broadband carrier DNS server cache
  5. If none of the preceding information is found, search for the DNS server, obtain the IP address and port number, and save the result in the cache

A TCP connection

TCP connection three handshake four wave

Browser rendering

Build a DOM tree

Byte -> string -> Token -> Node -> DOM

Build CSSOM tree

Byte -> String -> Token -> Node -> CSSOM

Building a Render tree

When the HTML parser encounters JavaScript while building the DOM, it pauses building the DOM, handing control to the JavaScript engine, and when the JavaScript engine runs, the browser resumes building the DOM where it left off. That said, if you want the first screen to render as quickly as possible, you should not load JS files on the first screen, which is why it is recommended to place the script tag at the bottom of the body tag. Of course, at the moment, it’s not necessary to put script tags at the bottom, because you can add defer or async properties to script tags. When the browser builds the DOM, if it encountered Style, it will execute JS after CSSOM is built. Normally, DOM and CSSOM are built in parallel, but when the browser encounters a script tag without defer or async properties, DOM construction will stop. If the browser has not finished downloading and building CSSOM at this point, Since JavaScript can modify CSSOM, it is necessary to wait for the completion of CSSOM construction before executing JS, and finally re-dom construction juejin.cn/post/695307…

draw

Calculate the size and position of each node on the screen based on the render tree. Repaint: When a change to the DOM results in a style change (such as changing the color or background color) without affecting its geometry, the browser does not need to recalculate the element’s geometry and simply draw a new style for the element. Relfow: When we modify the DOM to change the geometry of the DOM (such as changing the width, height, or hiding elements), the browser needs to recalculate the geometry of the element (and thus the geometry and position of other elements), and then draw the calculated results. This process is called reflux (also known as rearrangement)

algorithm

Bubble sort

function bubbleSort(arr) { if(! Array.isArray(arr)) return arr; if(arr.length < 2) return arr; for(let i = 1; i<arr.length ; i++) {console.log(i); const max = arr[0]; for(let j = 0; j< arr.length - i; j++) {console.log(arr[j], arr[j+1]) if(arr[j] > arr[j+1]) { const temp = arr[j+1]; arr[j+1] = arr[j]; arr[j] = temp; }}}}Copy the code

Merge sort

function _mergeSort(arr, result, start, end) { if (start >= end) return; let len = end - start, mid = start + Math.floor(len / 2); let start1 = start, end1 = mid, start2 = mid + 1, end2 = end; _mergeSort(arr, result, start1, end1); _mergeSort(arr, result, start2, end2); let k = start; while (start1 <= end1 && start2 <= end2) { result[k++] = arr[start1] < arr[start2] ? arr[start1++] : arr[start2++]; } while (start1 <= end1) { result[k++] = arr[start1++]; } while (start2 <= end2) { result[k++] = arr[start2++]; } for (let i = start; i <= end; i++) { arr[i] = result[i]; } return arr; } function mergeSort(arr) { if (! Array.isArray(arr) || arr.length < 1) return arr; return _mergeSort(arr, new Array(arr.length).fill(null), 0, arr.length - 1); }Copy the code

Quick sort

function selectionSort(arr) { if (! Array.isArray(arr) || arr.length < 2) return arr; for (let i = 0; i < arr.length; i++) { let minIndex = i; for (let j = i; j < arr.length; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; } } const temp = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = temp; } return arr; }Copy the code

Insertion sort

Heap sort

Digital reversal

int reversal(int n) {
    int m;
    while(n) {
        m = m * 10 + n % 10;
        n = n / 10; 
    }
    return m;
}
Copy the code

An array of merger

String parsing array

Enter ‘[1, 2, 3, 4, 5, [6, 7], 8], 9]’

Output [1, 2, 3, 4, 5, 6, 7], 8], 9]

function parse(str, arr = []) { if ( String.prototype.startsWith.call(str, "[") && String.prototype.endsWith.call(str, "]") ) { str = String.prototype.substring.call(str, 1, str.length-1) let temp = []; let strList = String.prototype.split.call(str, ',').map(item => item.trim()); let foundRight = 0; for (let i = 0; i < strList.length; i++) { if (temp.length && ! strList[i].endsWith("]")) { temp.push(strList[i]); } else if (strList[i].startsWith( "[")) { temp.push(strList[i]); } else if (strList[i].endsWith("]")) { foundRight++; if(foundRight === temp.filter(item => item.startsWith('[')).length) { temp.push(strList[i]); let ctx = []; arr.push(ctx)  parse(temp.join(','), ctx); temp = []; foundRight = 0; } else { temp.push(strList[i]) } } else { arr.push(strList[i]); } } } return arr; } The console. The log (parse (' [1, 2, 3, [[6, 7] 4, 5, 8], 9] '))Copy the code

The whole arrangement

const permute = (nums) => { const res = []; const used = {}; Function DFS (path) {if (path.length == nums.length) {res.push(path.slice()); // copy a path and add it to the solution set res return; } for (const num of nums) {// for enumerating each optional option // if (path.includes(num)) continue; // Don't write that! If (used[num]) continue; if (used[num]) continue; // If used, skip path.push(num); // Select the current number, add path used[num] = true; // Record DFS (path); // Recursive path.pop() based on the current number selected; Used [num] = false; used[num] = false; }} DFS ([]); // Recursive entry, empty path passed in return res; };Copy the code

React

SSR

Juejin. Cn/post / 684490…

key

Juejin. Cn/post / 684490…

The diff algorithm

Juejin. Cn/post / 684490…

Fiber

Juejin. Cn/post / 684490…

setState

Juejin. Cn/post / 684490…

hooks

Juejin. Cn/post / 684490…