Summary from cattle guest interview, through their own interview questions recorded in the interview process, summed up. There are many are written by themselves, hope to correct. Address: www.nowcoder.com/discuss/exp…

The 2021-9-15

If the throttle

Debounce: Multiple events are triggered within a specified period of time. Only one event is executed. Using zooming in the page window, the input box (this is not a real-time display of search results)

Throttle: Execute an event at a specified time. Use the monitor scrollbar to scroll through the input box (here is the real-time display of search results)

   / / image stabilization
    function debounce(fn, delay = 300) {
      const timer = null;
      return function () {
        // Clear the timer
        clearTimeout(timer);
        timer = setTimeout(() = > {
          fn.apply(this.arguments) }, delay); }}/ / throttling
    function throttle(fn, delay = 300) {
      let flag = true;
      return function () {
        // If the delay time is not reached, the fn function is not executed because flag=false
        if(! flag) {return;
        }
        flag = false;
        setTimeout(() = > {
          fn.apply(this.arguments)
          flag = true
        }, delay)
      }
    }
Copy the code

Supplement: When to use throttling and when to use anti-shake?

position

The CSS Position property is used to specify how an element is positioned in a document.

Attribute value relative, Absolute, fixed, or sticky. The default value is static, indicating that it is in the standard flow.

Set absolute, fixed, and elements are removed from the normal document flow.

Fixed: It is equivalent to the entire viewport offset, scroll bar scrolling, its position will not change. So it gives a kind of poor vision.

The sticky element is “fixed” to its nearest ancestor with a “rolling mechanism”.

Vue bidirectional binding

Use v-Model on form elements

Bind with the instruction V-model.

You do this by listening for the input event, and then setting the value of the reactive data to the currently entered value.

  • Text and Textarea elements are usedvalueThe property andinputEvents;
  • Checkbox and radio usecheckedThe property andchangeEvents; Determine the selected state of a form element because of the Checked property. But the V-Model binds the corresponding value. Checkbox is checked, checked is bound, and checked is bound to an array. Time value of the radio binding.
  • The select field willvalueAs prop and willchangeAs an event. The V-Model binds to an array.

Use v-Models on custom elements

We need to define prop in the component (the default binding is the modelValue property name) and send custom events (Update :modelValue).

But we can change the name of a prop property to use the V-model directive more than once in a component.

v-model:title="title"

Vue responsive principle

Juejin. Cn/post / 702140…

Vue2 is implemented via Object.defineProperty().

Vue3 is implemented by proxy.

Vue diff algorithm

Compare old and new vNodes

Juejin. Cn/post / 702042…

The specified key

  • Iterate from the beginning, continue to meet the same node, meet different jump out of the loop
  • Start from the end of the traverse, encounter the same node to continue, meet different jump out of the loop
  • If there are more new nodes, add nodes
  • If there are more new nodes, then the nodes are removed
  • If there is a sequence of positions in the middle that you do not know how to arrange, then the key is used to build the index graph to maximize the use of old nodes.

The HTTP status code

HTTP Status Code: a 3-digit Code used to indicate the Status of the web server hypertext Transfer protocol (HTTP) response.

The function of HTTP status code is that the server tells the client the status of the current request response. By status code, you can judge and analyze the running status of the server.

The following are some applicable scenarios of status codes:

  • 100: Before sending POST data to the server, the client asks the server whether the server processes the POST data. If the server does not process the POST data, the client does not upload the POST data. If the server processes the POST data, the client uploads the POST data. It is used for POST big data transmission
  • Generally used for breakpoint continuation, or for loading large files such as video files
  • 301: Permanent redirects are cached. The new domain name replaces the old domain name. If the old domain name is no longer in use, users can use 301 to redirect to the new domain name
  • 302: Temporary redirection is not cached and is often used when unlogged users access the user center and redirect to the login page
  • 304: negotiation cache, tell the client there is a cache, directly use the cache data, return page only header information, is no content part
  • 400: The request cannot be identified by the server because the parameter is incorrect
  • 403: This field is returned when the client is told to access the site or resource in decimal format, for example, on the Internet, and then access the site or resource only through an Intranet IP address
  • 404: The server cannot find the resource, or the server rejects the request without explaining why
  • 503: When the server is down for maintenance, use 503 to respond to requests or nginx to set the rate limit. If the rate limit is exceeded, 503 will be returned
  • 504: The gateway times out

classification

The first digit of the status code determines different response states, including the following:

  • 1: message
  • 2 indicates success.
  • 3 indicates redirection
  • 4 indicates that the request is incorrect
  • 5 indicates a server error

1xx

The delegate request has been accepted and needs to continue processing. This type of response is a temporary response, containing only the status line and some optional response header information, and ending with an empty line

Common ones are:

  • 100 (the client continues to send the request, which is a temporary response) : This temporary response is used to inform the client that some of its requests have been received by the server and have not yet been rejected. The client should continue to send the rest of the request, or ignore the response if the request is completed. The server must send a final response to the client after the request completes
  • 101: The server switches protocols based on client requests, mainly used for WebSocket or HTTP2 upgrades

2xx

Indicates that the request was successfully received, understood, and accepted by the server

Common ones are:

  • 200 (success) : The request was successful and the desired response header or data body will be returned with this response
  • 201 (Created) : The request succeeded and the server created a new resource
  • 202 (Created) : The server has received the request but has not yet processed it
  • 203 (Unauthorized information) : The server successfully processed the request, but the information returned may have come from another source
  • 204 (no content) : The server successfully processed the request, but did not return anything
  • 205 (reset content) : The server successfully processed the request, but did not return anything
  • 206 (Partial) : The server successfully processed some requests

3xx

Indicates that further action is required to complete the request. Typically, these status codes are used for redirects

Common ones are:

  • 300 (multiple options) : The server can perform multiple operations on a request. The server can select an operation based on the requester (User Agent) or provide a list of operations for the requester to select
  • 301 (Permanent move) : The requested page has been permanently moved to a new location. When the server returns this response (a response to a GET or HEAD request), it automatically forwards the requester to the new location
  • 302 (Temporary movement) : The server is currently responding to requests from web pages in different locations, but the requester should continue to use the original location for future requests
  • 303 (Look at other locations) : The server returns this code when the requester should use a separate GET request for a different location to retrieve the response
  • 305 (using a proxy) : The requester can only access the requested web page using a proxy. If the server returns this response, it also indicates that the requester should use a proxy
  • 307 (temporary redirection) : The server currently responds to requests from web pages in different locations, but the requester should continue to use the original location for future requests

4xx

Represents that the client appears to have made an error that interferes with the server’s processing

Common ones are:

  • 400 (error request) : The server does not understand the syntax of the request
  • 401 (unauthorized) : Request requires authentication. The server may return this response for a web page that requires login.
  • 403 (Forbidden) : The server rejected the request
  • 404 (not found) : The server could not find the requested page
  • 405 (method disabled) : Disables the method specified in the request
  • 406 (not accepted) : Web page that cannot respond to a request using the requested content features
  • 407 (Proxy authorization required) : This status code is similar to 401 (unauthorized), but specifies that the requester should authorize the use of the proxy
  • 408 (Request timeout) : Timeout occurred while the server was waiting for a request

5xx

Indicates that the server is unable to complete an obviously valid request. This type of status code indicates that an error or exception has occurred while the server is processing the request

Common ones are:

  • 500 (server internal error) : The server encountered an error and could not complete the request
  • 501 (not yet implemented) : The server does not have the capability to complete the request. For example, the server may return this code if it does not recognize the request method
  • 502 (error gateway) : The server acting as a gateway or proxy received an invalid response from the upstream server
  • 503 (Service unavailable) : The server is currently unavailable (due to overloading or downtime for maintenance)
  • 504 (gateway timeout) : The server acts as a gateway or proxy, but does not receive the request from the upstream server in time
  • 505 (HTTP version not supported) : The server does not support the HTTP protocol version used in the request

Js array methods, which can change the array itself

Add: push, unshift, splice, concat. The first three can change the original array.

Delete: pop, shift, splice, slice. The first three can change the original array.

Change: the splice

Check: includes, findIndex, find, indexOf.

Other: join The given string joins each element.

ForEach, map, some, every, filter,reduce

line-height

Set the amount of space for multi-line elements.

Set the line height equal to height to center the text vertically.

Adaptive center

  1. margin: auto;
  2. flex
  3. text-align
  4. Position + transform, position + negative margin

Selector priority

Weights can be specified by numerical values.

! Important means infinity

Inline: 1000

Id: 100

Class: 10

Tags: 1.

Wildcards, subclass selectors, and sibling selectors, such as *, >, +, have weights of 0

Inherited styles have no weights

The singleton pattern

class Person {
      constructor(name) {
        this.name = name;
        this.p = null
      }
​
      static instance(name) {
        if (!this.p) {
          this.p = new Person(name)
        }
        return this.p
      }
    }
Copy the code

Webpack packaging process

By specifying the entry file and output file (filename, path) in webpack.config.js, since webpack can only pack JS and JSON files, Therefore, we can use Loader and plugin to extend the Webpack packaging, so that it can pack pictures, CSS and other resources, we can also optimize the packaging project according to the development environment and production environment, and then through the Webpack command to pack.

The 2021-9-16

Let, the scope of const

var temp = 123;
if (true) {
  temp = 'abc';
  // Cannot access 'temp' before initialization. What he means is that temp cannot be used before declaration in a block-level scope. That is, assign temp.
  let temp;
  console.log(temp) // Cannot access 'temp' before initialization
}
Copy the code

Horizontal and vertical center

  1. The text – align: center. On loading the parent element, it can center the text of inline elements, inline block elements, and block-level elements.
  2. Margin: auto. Sets the element horizontally centered relative to its parent. But the element needs to be set to a width.
  3. Display: flex. Horizontal and vertical centers can be set.
  4. Padding-top === padding-bottom: Center text vertically in inline and inline block elements.
  5. Child elements use absolute layouttop: 50%; left: 50%And then I’m going to use negative thetamargin-top, margin-leftPull the child up half the way,Block-level elementsHorizontal and vertical.But you need to know the width and height of the child elements.
  6. Child elements use absolute layouttop: 50%; left: 50%And then I’m going to use negative thetatransform: translate(-50%, -50%)Pull the child up half the way,Block-level elementsHorizontal and vertical.You don’t need to know the width and height of the child elements.
  7. Margin: auto; margin: auto; margin: auto; The child element needs a width and height.
  8. Set parent element height == line-height, text-aligin = center. Display: inline-block; . You don’t need to know the width and height of the child elements.

Closures, disadvantages

The inner function accesses the variables of the outer function. Although the execution environment of the function is freed, the variables introduced by the internal function are not freed and remain in memory, so a memory leak occurs. Solution: Delete all unused local variables before exiting the function.

Features of arrow function

The arrow function has no prototype, so the arrow function itself has no this. Arrow functions cannot be used as constructors

Syntax is more concise and clear

Call | apply | bind cannot change the arrow point of this function

Arrow functions do not bind arguments and use rest arguments instead… Instead of the Arguments object, access the argument list of the arrow function

Arrow functions cannot be used as Generator functions and the yield keyword cannot be used

Inside the arrow functionthisIs defined in the upper scopethis.

Achieve a two-column layout

Zhuqingguang. Making. IO / 2017/08/16 /…

Flex layout

The grid layout

Floating. Width: calc(100% – width of the last floating element). One thing to note here, float element, if one row is not wide enough for another float element to line up, then it will line up on the next row. This is due to the float element triggering the BFC. They can’t cover each other.

float+margin-left

absolute+margin-left

float+BFC

Vue life cycle

setup -> beforeMount -> mounted -> beforeUpdate -> updated -> beforeUnmount -> unmounted

Methods for component communication

Props, custom events, provide and Inject, route parameters,

  • props
  • $emit
  • ref
  • $attrs
  • v-model
  • provide / inject
  • Vuex

The two arrays are merged and the duplicate elements are removed

concat + new Set()

const arr1 = [1, 2, 1, 90, 4, 8, 8];

const arr2 = [2, 6, 7, 88, 1, 1];

const arr = arr1.concat(arr2);

console.log([…new Set(arr)])

Cross-domain approach

jsonp

cors

Webpack server agent

Nodejs middleware proxy

PostMessage, socket

Iframe and some other extensions

The json. Can only resolve cross domain of GET

Cors: You can enable CORS by setting access-Control-allow-Origin on the server. This attribute indicates which domain names can access resources. If a wildcard is set, all websites can access resources.

Reverse proxy in VUE

Node middleware proxy (twice across domains) : The same origin policy is the standard that browsers need to follow, not the same origin policy if the server is requesting from the server. http.request

postMessage

PostMessage is an API in HTML5 XMLHttpRequest Level 2, and is one of the few window properties that can operate across domains. It can be used to solve the following problems:

  • Data transfer between the page and the new window it opens
  • Messaging between multiple Windows
  • Page with nested IFrame message delivery
  • Cross-domain data transfer for the three scenarios above

The postMessage() method allows scripts from different sources to communicate asynchronously in a limited manner, enabling cross-text file, multi-window, cross-domain messaging.

otherWindow.postMessage(message, targetOrigin, [transfer]);

  • Message: Data to be sent to another window.
  • TargetOrigin: Specifies which Windows can receive message events via the origin property of the window. The value can be a string “*” (for unrestricted) or a URI. If any of the protocol, host address, or port of the target window does not match the value provided by targetOrigin, the message will not be sent. A message will only be sent if all three match.
  • Transfer (Optional) : A string of Transferable objects that are transferred at the same time as Message. Ownership of these objects is transferred to the receiver of the message, and ownership is no longer retained by the sender.

How to encapsulate a component

Component three elements: props, Slot, and custom events. CSS uses scoped to control the scope of CSS.

Benefits of componentized development:

  • Componentization is the layering of implementation and is a more efficient way to combine code
  • Componentization is the reorganization and optimization of resources so as to make project resource management more reasonable
  • Componentization is good for unit testing
  • Componentization is friendly to refactoring

Use the following principles whenever possible, and the more you use them, the more reusable your components will be.

  1. Apply the principle of single responsibility
  2. Apply the principle of openness and closure
  3. Go for the short and the sharp
  4. Avoid too many parameters
  5. The scope of trust should be narrowed and trust should be stabilized
  6. Single Point Of Truth applies The Rule Of SPOT.
  7. Pursue no side effects
  8. Pursue referential transparency
  9. Avoid exposing component internal implementations
  10. Avoid manipulating the DOM directly
  11. Don’t call us, we’ll call you, IoC, Inversion of control
  12. The entry checks the validity of the parameters and the exit checks the correctness of the returns
  13. Fully isolate the changing parts
  14. Component and data sharing, trust consistent data structures