Chunzhao got to know an outstanding undergraduate student named White Bear C through the front group of Ruochuan Big man. He was full of strength and luck and had a lot of offers. Finally, he chose the byte with far wider strength and prospect.

[🌼 byte side: 41min]

1. Introduce company projects

2. Describe the difference between hooks in React and class

The main difference is: Mental model

Hooks are more functional and declarative.

Shifting from imperative to declarative, Hooks provide a variety of declarative side effects apis (useEffect, use allback) that make “lifecycle” a “low-level concept” that is insensitive to developers, so developers can focus on higher levels of abstraction.

Hooks component is to reduce the use of the react development difficulty, let novice can not use the class components still can undertake project development, may not need to consider this problem, can need not use high order component reuse can still functions.

3. Say something about the output

 alert(a);
 a();
 a = 3;
 function a (){
     alert(10)
 }
 alert(a);
 a = 6;
 a()
Copy the code

The answer:

// The first output
function(){
	alert(10)}// Second output
10
// The third output
3
// Fourth output
Uncaught TypeError: a is not a function
    at <anonymous> : willCopy the code

4. How to learn the front end

5. How to get the results of both apis at the same time, by handPromise.all()

First, we need to know that the promise.all () method takes an iterable of promises and an array of Promise objects as arguments. When all Promise objects in the array become Resovled, the whole promise.all () state is Resolved. Promise.all() is in the Rejected state if there is a Promise object in the Rejected state.

That is, Promise. All needs to wait until all the states of Promise become a big pity. Then resolve, but as long as one Promise fails, the result of failure will be returned.

Promise.all is characterized by:

  • Receives an array of Promise instances or an object with an Iterator interface
  • Resolve becomes a Promise object if the element is not a Promise object
  • If everything succeeds, the state becomes Resolved and the returned values are passed as an array to the callback
  • Once there is a failure, the state becomes Rejected and the return value is passed directly to the callback
  • The return value of promise.all () is also a new Promise object
Promise.all = function(arr){
    return new Promise((resolve,reject) = > {
        if(!Array.isArray(arr)){
            return reject(new TypeError('arguments must be an array'));
        }
        let length = arr.length;
        let resolveNum = 0;
        let resolveResult = [];
        for(let i = 0; i < length; i++){
            arr[i].then(data= > {
                resolveNum++;
                resolveResult.push(data)
                if(resolveNum == length){
                    return resolve(resolveResult)
                }
            }).catch(data= > {
                return reject(data)
            })
        }
    })
}
Copy the code

6. Talk about processes and threads

Official:

  • Process: A process is the smallest unit of CPU resource allocation.
  • Thread: A thread is the smallest unit of CPU resource scheduling.

Personal Understanding:

  • Processes: In an operating system, resources are allocated to programs that run independently of each other, each responsible for running its own code.
  • Threads: When the operating system frequently creates and destroys processes, resources need to be allocated and reclaimed frequently, and time and resources are consumed in the process. However, with the upgrading of computer hardware, the emergence of multi-core CPU with large memory can reasonably schedule the computer memory resources according to the demand, and threads have gradually replaced processes.

Operating system process diagram:

Thread graph for operating system:

7. Browser caching mechanism

Typically, browsers have two caching strategies: strong caching (cache-control) and negotiated caching (last-Modified, Etag), and both are implemented by setting HTTP headers.

The browser cache process is:

  1. When the browser loads the resource for the first time, the server returns 200. The browser downloads the resource file from the server and caches the response header and the return time of the request.
  2. The next time a resource is loaded, the time difference between the current time and the last time it was returned to 200 is compared. If it does not exceed the max-age set by cache-control, the file has not expired, hits the strong cache, and reads the file directly from the local cache (if the browser does not support HTTP1.1, Expires is used to determine whether it expires. If the time expires, a header request with if-none-match and if-modified-since is sent to the server;
  3. After receiving the request, the server determines whether the requested file is modified according to the Etag value. If the Etag value is consistent, the requested file is not modified and matches the negotiation cache, and 304 is returned. If not, change it, return the new resource file with the new Etag value and return 200;
  4. If the server receives a request with no Etag value, it compares if-modified-since with the last modification time of the requested file. If the request is consistent, the negotiation cache is matched and 304 is returned. If not, the new last-Modified and file is returned and 200 is returned;

8. Cookie and localStorage, sessionStorage differences

cookie sessionStorage localStorage
The life cycle You can set the expiration time. If you do not set the expiration time, the browser is closed by default Valid only for the current web session and will be cleared when the page or browser is closed. It will be saved permanently unless it is manually removed.
To store data About 4 KB It can hold up to 5MB of information. It can hold up to 5MB of information.
The HTTP request This is carried each time in HTTP headers, and using cookies to store too much data can cause performance problems It is saved only in the client (browser) and does not communicate with the server It is saved only in the client (browser) and does not communicate with the server
Ease of use Requires the programmer to encapsulate, the source Cookie interface is not friendly The source interface is acceptable and can be repackaged to provide better support for objects and arrays The source interface is acceptable and can be repackaged to provide better support for objects and arrays

9. How to implement single sign-on

Single sign-on (SSO) : Single sign-on (SSO for short) means that if you log in to one system in a multi-system application cluster, you can obtain authorization from all other systems without logging in to this system. In simple terms, single sign-on (SSO) means that in multiple systems, a user only needs to log in once, and each system can perceive that the user has logged in.

The specific steps are:

  • (1) When A user accesses the protected resources of system A and does not log in to system A, the system carries the address of system A and forwards the login request to the SSO authentication center.
  • (2) If the SSO authentication center detects that A user has not logged in, it directs the user to the login page of system A.
  • (3) The user should enter the user name and password to log in and submit the application;
  • (4) The SSO authentication center verifies the user name and password, creates a global session between the user and the SSO authentication center, and creates an authorization Token.
  • (5) The SSO authentication center with the Token jumps to the original request address (the address of system A);
  • (6) When it is used to initiate A request, System A obtains the Token and goes to the SSO authentication center to verify whether the Token is valid;
  • (7) The SSO authentication center verifies the Token and registers the address of system A if it is valid.
  • (8) System A uses the Token to create A session with the user, which becomes A local session and returns the protected resource.
  • (9) When a user accesses the protected resources of system B and does not log in, the user carries the address information of system B and forcibly switches the login to the SSO authentication center.
  • (10) When the SSO authentication center detects that the user has logged in, the SSO authentication center redirects to the address of system B with the Token.
  • (11) When a request is made to system B, system B obtains the Token and goes to the SSO authentication center to verify whether the Token is valid.
  • (12) If the SSO authentication center validates the Token, the address information of system B is registered.
  • (13) System B uses the Token information to enter a partial session with the user and returns the protected resource to the browser.

After a user logs in successfully, sessions are established with the SSO authentication center and each subsystem. The sessions established between the user and the SSO authentication Center become global sessions, and those established between the user and each subsystem are called local sessions. After a local session is established, users do not access subsystem protected resources through the SSO authentication center.

11. Tell me about the difficulties you encountered during the project

12. Determine whether it is a palindrome number

12.1 Use higher-order functions

First convert A number to string A, then to array, then to array B, then to array B.

/ * * *@param {number} x
 * @return {boolean}* /
function isPalindrome(x) {
    if ( x < 0 ) return false
    let str = ' ' + x
    return Array.from(str).reverse().join(' ') === str
};
Copy the code

12.2 Loop through an Array of Strings from back to front

Convert A number to string A, loop string A from back to front, concatenate the looping characters into A new string B, compare strings A and B, and draw A conclusion.

/ * * *@param {number} x
 * @return {boolean}* /
function isPalindrome(x) {
    let str = x + ' '
    let newStr = ' '
    for(let len = str.length, i = len - 1; i >= 0 ; i--) {
        newStr += str[i]
    }}
    return newStr === str
};
Copy the code

12.3 Use the middle number as a node to determine whether the left and right ends are equal

Take the middle number as the node, judge whether the left and right sides are equal.

function isPalindrome(x) {
    if ( x < 0|| (x ! = =0 && x % 10= = =0)) {
        return false
    } else if ( 0 <= x && x < 10) {
        return true
    }
    x = ' ' + x
    for(let i = 0 ; i < x.length/2; i++) {
        if(x[i] ! == x[x.length - i -1]) {
            return false}}return true
};
Copy the code

γ€πŸŒ΄ bytes two faces 60 min】

1. How to learn the front end and what books have you read

2. How do processes communicate with threads

With one side

3. Click the cells in the table to get the contents

//1. Get cell contents

let table = document.getElementById("myGrid");Β 
let content = table.rows[i].cells[i].innerHTML;

//2. Get the contents of the input box in the cell
table.rows[1].cells[2].childNodes[0].value;
Copy the code

4. Implement publish subscribe, on, emit, off, clear one of the methods

Ideas:

  • Create an object
  • Create a cache list on this object (dispatch center)
  • The on method is used to add the function fn to the cache list (subscribers register events with the dispatch center).
  • The emit method takes the first name in the arguments as an event and executes functions in the cache list based on the event value (the publisher issues the event to the scheduler, which processes the code).
  • The off method can unsubscribe (unsubscribe) based on the event value
  • The once method listens only once and deletes the cache function (subscribe once).

Code:

The ON and emit methods are implemented

// Create an object
let eventEmitter = {};

// Cache list for event and fn
eventEmitter.list = {};

/ / subscribe
eventEmitter.on = function (event, fn) {
    let _this = this;
    // If there is no corresponding event value in the object, that is, there is no subscription, create a cache list of events
    // If there is a corresponding event value in the object, add fn to the cache list of the corresponding event
    (_this.list[event] || (_this.list[event] = [])).push(fn);
    return _this;
};

/ / release
eventEmitter.emit = function () {
    let _this = this;
    // The first argument is the corresponding event value, which is fetched directly with the shift method of the array
    let event = [].shift.call(arguments),
        fns = [..._this.list[event]];
    Return false if there is no fn in the cache list
    if(! fns || fns.length ===0) {
        return false;
    }
    // Iterate through the cache list corresponding to the event value, executing fn in sequence
    fns.forEach(fn= > {
        fn.apply(_this, arguments);
    });
    return _this;
};

function user1 (content) {
    console.log('User 1 subscribes to :', content);
};

function user2 (content) {
    console.log('User 2 subscribes to :', content);
};

/ / subscribe
eventEmitter.on('article', user1);
eventEmitter.on('article', user2);

/ / release
eventEmitter.emit('article'.'Javascript publish-subscribe ');

/* User 1 subscribes to Javascript publish-subscribe mode user 2 subscribes to Javascript publish-subscribe mode */

Copy the code

5. Class protected, pravila and public

  • Public modifies properties that can be accessed from anywhere. The default value is global
  • A private modified property can only be accessed inside a class, while a private property can be accessed inside a class. Private attributes can be accessed outside the class by adding a Set GET accessor to the class
  • Protected properties can only be accessed within the current class and its subclasses. Protected properties can only be accessed within the scope of the current class and its subclasses

6. Cross domain

  • JSONP: Used in HTML
  • Cross-domain resource sharing (CORS) : You can enable CORS by setting access-Control-Allow-Origin on the server
  • Document. domain: This mode can be used only when the secondary domain names are the same
  • PostMessage: This is typically used to fetch third-party page data embedded in a page. One page sends the message, and the other determines the source and receives the message
  • Nginx reverse proxy implementation across domains
  • window.name + iframe

7. Cors principle

The cross-domain principle of CORS is that the browser and server make some conventions and restrictions through some HTTP protocol headers.

Protocol headers associated with cross-domain

Request header instructions
Origin Indicates the source URI of the precheck request or actual request, regardless of whether the ORIGIN field is always sent across domains
Access-Control-Request-Method Tell the server the HTTP method used for the actual request
Access-Control-Request-Headers Tells the server the header field carried by the actual request
Response headers instructions
Access-Control-Allow-Origin Specifies the outdomain URI that is allowed to access the resource. Wildcard * is not allowed for credential requests
Access-Control-Expose-Headers Specifies the response header accessible to the getResponseHeader of XMLHttpRequest
Access-Control-Max-Age Specifies how long the results of a preflight request can be cached
Access-Control-Allow-Credentials Whether to allow the browser to read the content of the response; When used in response to a preflight precheck request, specifies whether the actual request can use the credentials
Access-Control-Allow-Methods Specifies the HTTP method allowed for the actual request
Access-Control-Allow-Headers Specifies the header field allowed in the actual request

8. Forward and reverse proxies

Forward proxy: is a server located between the client and the origin server (Origin Server). In order to get content from the origin server, the client sends a request to the proxy and specifies the destination (origin server). The proxy then forwards the request to the origin server and returns the content to the client. Clients must make some special Settings to use forward proxies.

Reverse proxy: The actual operation mode of Reverse Proxy refers to that the Proxy server receives Internet connection requests, forwards the requests to the server on the internal network, and returns the results obtained from the server to the client requesting Internet connection. In this case, the proxy server behaves as a server.

9. Login process, state persistence

With one side

10. How to use token

  • 1. The client uses the user name and password to request login
  • 2. The server receives a request to verify the user name and password. After the authentication succeeds, the server issues a Token and sends the Token to the client
  • 3. After receiving the Token, the client can store it, for example, in a Cookie or LocalStorage. Each time a client requests resources from the server, it must carry a Token signed by the server
  • 4. The server receives the request and verifies the Token contained in the request. If the verification succeeds, the server returns the requested data to the client

11. Identify object and array methods

Method to determine Array:

// The safest way
Object.prototype.toString.call([1.2.3])	// "[object Array]"

/ / instanceof method
[1.2.3] instanceof Array

// if a = null, the constructor will return an error.
[1.2.3].constructor === Array;//true

// Check how the prototype is constructed
[1.2.3].__proto__.constructor === Array
Copy the code

Method to determine Object:

// The safest way
Object.prototype.toString.call({a: 123})	// "[object Object]"

// if a = null, the constructor will return an error.
var o = {a: 123};
o.constructor === Object;   / / true object

/ / instanceof method
var n2 = new Number(123)  // now n2 is an object element!
typeof n2;				 // "object"
n2 instanceof Number;	  // true
Copy the code

Algorithm of 12.

Permutations and combinations of non-repeating strings. Write a method that evaluates all permutations of a string in which each character is different.

Example:

Enter: S ="qwe"Output:"qwe"."qew"."wqe"."weq"."ewq"."eqw"] Time complexityCopy the code

πŸ‘‹ three bytes 35min

1. React and Vue design ideas

2. Common status codes

Status code Status code English name Product description
200 OK The request is successful. Typically used for GET and POST requests
204 No Content No content.The server processed successfully, but did not return content. You can ensure that the browser continues to display the current document without updating the web page
206 Partial Content Is a request for a portion of a resource, the server successfully processes some GET requests, and the response messages contain the entity Content in the Range specified by Content-Range.
301 Moved Permanently Permanent redirection. The requested resource has been permanently moved to the new URI, the return message will include the new URI, and the browser will automatically redirect to the new URI. Any future new requests should be replaced with a new URI
302 Found Temporary redirection. Similar to 301. But resources are moved only temporarily. The client should continue to use the original URI
303 See Other View other addresses. Similar to 302. Use the GET request to view
304 Not Modified Unmodified. The requested resource is not modified, and the server does not return any resources when it returns this status code. Clients typically cache accessed resources by providing a header indicating that the client wants to return only resources that have been modified after a specified date
307 Temporary Redirect Temporary redirection. Similar to 302. Using GET requests for redirection does not change from POST to GET, as per browser standards.
400 Bad Request A syntax error occurs in the client request packet, which the server cannot understand. Procedure. Will browsers treat this state as if it were 200 OK
401 Unauthorized The request requires user authenticationIs authenticated through HTTP (BASIC authentication, DIGEST authentication). If a request has been made before, the user fails to be authenticated
402 Payment Required Reserved for future use
403 Forbidden The server understands the request from the requesting client, but refuses to execute the request
404 Not Found The server could not find the resource (web page) based on the client’s request. With this code, a web designer can set up a personalized page that says “the resource you requested could not be found.” It can also be used when the server rejects the request without giving a reason
500 Internal Server Error The server had an internal error and could not complete the requestOr the Web application may have a bug or some temporary fault
501 Not Implemented The server did not support the requested functionality and could not complete the request
503 Service Unavailable The server is temporarily unable to process client requests due to overloading or system maintenance. The length of the delay can be included in the server’s retry-after header

3. Negotiate cache

With one side

4. Publish/subscribe vs. Observer mode

Observer mode: The Observer directly subscribes to the Subject, and when the Subject is activated, it fires events within the Observer.

Publish and subscribe model: Subscriber registers the event they want to Subscribe to the dispatch center. When Publisher publishes the event to the dispatch center, that is, when the event is triggered, The processing code registered with the dispatch center by the Fire Event subscriber.

5. Webpack design concept

It is a module packer, which can also be explained by referring to a picture on the official website. We can see webPack, which can analyze the dependencies of each module, and finally package into the common static files,.js,.css,.jpg,.png. Webpack is a management tool used by the front end to build files. It can package files created by various plug-ins and files of various versions of resources into code and resource files compatible with browsers of various versions. Webpack is a plug-in tool that relies on NPM creation.

  • The specific process is:
    1. First the various module files are imported into the WebPack configuration file
    2. Module files are parsed into chunk code blocks, and the relationship between each module is statically analyzed
    3. Package various files based on module dependencies into files recognized by browsers of various versions
    4. Configure the browser entry file bundle

6. Webpack plugin is different from Loader

  • Loader: WebPack handles JS and JSON files by default. Loader configures WebPack to handle other types of files, turn them into valid modules for application use, and add them to dependency diagrams.
  • Plug-in plugin: Loaders are used to transform certain types of modules, while plug-ins are used to perform a wider range of tasks. For example: package optimization, resource management, injection of environment variables, etc.

7. The prototype chain

8. Project difficulties

9. Event loops

meet

10. Implementing deepClone(consider circular references)

  • Shallow copy: Refers to the assignment of an attribute value from one object to another. If an attribute value is of reference type, the address of the reference is assigned to the object, so that both objects have a reference of the same reference type. Shallow copies can be implemented using object. assign and expansion operators.

  • Deep copy: If it encounters an attribute of a reference type, it creates a new reference type and assigns the corresponding value to it, so the object gets a new reference type instead of a reference of the original type. Deep copy can be implemented using JSON’s two functions for some objects, but since JSON’s object format is more strict than JS’s, the conversion will fail if the attribute value contains a function or Symbol value.

    function deepCopy(obj){
    	// Check whether the current input object is an array or an object
    	let newObj = obj instanceof Array ? [] : {};
    	for(const [key,value] of Object.entries(obj)){
    		newObj[key] = typeof value === "string" ? deepCopy : value;
    	};
    	return newObj;
    };
    Copy the code

【πŸ”₯ 】

  1. Browser cache mechanism: juejin.cn/post/684490…
  2. The single sign-on: mp.weixin.qq.com/s/WgRujrI9W…
  3. The browser cache mechanism: www.cnblogs.com/suihang/p/1…
  4. Forward proxy and reverse proxy: juejin.cn/post/684490…
  5. Principle of CORS: juejin.cn/post/684490…
  6. Check the Array method: juejin.cn/post/684490…

If you have any suggestions or questions about the shortcomings of this blog post, you can discuss them in the comments section at ✌️

Sorting is not easy, remember to pay attention to, like πŸ‘ support oh ~ 😘