preface

The following topic is I read dozens of interviews, picked out I can’t test questions. Because I also participated in the spring recruitment so long, the hot examination questions almost have seen, there are many on the market, I will share some of my first glance not or may not be clear about the topic! The answer is their own hundred degrees and then summarized, there may be some deviation, welcome to correct.

The body of the

JavaScript

  1. Advantages and disadvantages of weakly typed languages
  1. In contrast to strongly typed languages, it allows implicit conversions, which is a double-edged sword. If you can see what’s happening, it doesn’t matter
  2. Coding is very convenient, in the development of the need not to pay too much attention to the problem of data type, can improve the efficiency of logic development. Strongly typed languages, for example, can be deadly when it comes to data requests, data types or interfaces that need to be defined, and data structures that are really hard to deal with
  3. Memory utilization is not as high as in strongly typed languages, where more memory is allocated for general purpose purposes, whereas strongly typed languages are defined
  1. The meaning of the third and fourth parameters of addEventListener

Both parameters specify the timing of the time callback, true -> when the time is captured, false -> when the event is bubbled, and whoever is written first takes effect. For other details, see MDN

  1. Onload is executed after all resources including images have been loaded
  2. The Document. ready method is executed after the DOM tree is loaded, whereas window.onload is executed after page resources (such as images and media resources, which load much more slowly than the DOM) are loaded. That is, $(document).ready is executed before window.onload
  1. Web Security, can CSRF tokens be stored in cookies?

CSRF tokens are a way to counter CSRF attacks. A CSRF attack is simply a hacker taking your cookie and faking your login status, so it’s called cross-site request forgery. In this case, it should be no, but the answer is yes, you can read this article, the premise of cookie is http-only, that is, cookie can only be transmitted under HTTP,js script will not be able to read cookie information.

  1. Let’s talk about map data structure design from the ground up. What if the capacity is insufficient? It may take a lot of time during capacity expansion. What if I need to access the capacity during capacity expansion

How to achieve O(1) add, delete and check

  1. Array plus linked list to store data
  2. Converts key values to hashCode using a hash function
  3. Convert hashCode to an array index by adding to the length of the arrayhashCode & (length - 1)(Modulus is also ok, but not as efficient as and operation).
  4. What if there’s a conflict? If there’s a conflict, add a linked list

capacity

The default map size is 16, and the default loadFactor value is 0.75. That is, the capacity expansion is performed when the array usage in the map reaches 16 x 0.75 by default. The time of array expansion is O(n), and then you have to recalcate the relation between hashCode and array index. So if you know the size in advance, you can assign the initial value new Map(1000).

Why the default length is a power of 2

Since hashCode & (length-1) is used for mapping, when length is a power of 2, the binary values of length-1 are all 1, which can greatly reduce conflicts, so expansion is usually doubled

  1. Error trapping
  1. Sync error capture sync error capture with try… The catch ()
  2. Asynchronous error catching Asynchronous error catching For example, if an error occurs in a callback function, the error cannot be caught outside the callback function. In the case of a promise, a promise provides a catch to catch errors, either reject or syntactic errors. Async await error catching and synchronization error using try… I’ll catch it
  3. Don’t forget the onError event and the act-16 error bound, which adds a new life cycle method componentDidCatch(error, info)
  1. How does REACT differ from MVVM?

To a ruan yifeng teacher’s picture, everything is clear!

React architecture: Personally, React emphasizes one-way data flow
State –> View –> New State –> New ViewI would say m-V architecture, state-driven view.

  1. Extension, sealing, and freezing of ES5 objects
  1. Object. PreventExtensions Prevent Object extensions and make an Object unextensible, meaning never add new properties
  2. Seal (), a closed Object, is non-extensible, and its members [[64x]] feature is set to false. The properties and methods cannot be deleted, and the accessor properties cannot be modified using object.defineProperty ().
  3. Freeze (): Both unextensible and sealed. The object data attribute [[Writable]] property is set to false. Accessor properties are still writable if the [[Set]] function is defined.
  1. ==, ===

Except in special cases, the comparison of == will cause the two edges to get to know each other and then compare. Return false for different values, false for different types, and compare addresses by reference

== conversion rule

  1. If there is a Boolean, convert them into digital, 0 | | 1
  2. If a string, a number, converts the string to a number
  3. If the two are objects, the addresses are compared
  4. If one is a reference type variable and one is not, the valueof() method, or the toString() method, that references the type variable is called

Other rules

  1. Null and undefined are equal
  2. Null and undefined cannot be converted to any other value until equality is compared
  3. If one of the operands is NaN, the equality operator returns false and the unequal operator returns true. Important: The equality operator returns false even if both operands are NaN; Because NaN is not NaN by rule
  4. If both operands refer to the same object, the equality operator returns true; if both operands refer to the same object, the equality operator returns true. Otherwise, return false
  1. Array.sort() internal algorithm

Sort uses a combination of insertion sort and quicksort. If the array length is less than 10, insert sort is used. Use quicksort for lengths greater than 10. It’s more efficient to insert sorts in arrays that are short. Once you answer this, be prepared to be asked about time complexity calculations and the principles of quicksort

  1. ES5 inheritance and ES6 inheritance
  1. ES5 inherits the base method through Prototype, then creates subclass instances and adds superclass attributes to thisParent.apply(this)
  2. ES6’s inheritance mechanism essentially creates an instance object of the superclass, this(so you must call the super() method of the superclass first), and then modify this with the constructor of the subclass. ES6 defines classes using the class keyword, which contains constructors, and extends classes through the extends keyword. Subclasses must call the super method from the constructor method, otherwise new instances report an error. Because subclasses don’t have their own this object, they inherit this from their parent class and then call it. If you don’t call super, subclasses don’t get this.
  1. Why SRC requests for script tags do not cross domains, but asynchronous requests from Ajax do

The same origin policy is an important security policy that restricts how an Origin document or the scripts it loads can interact with resources from another source. It can help block malicious documents and reduce the number of vectors that can be attacked. The same origin policy controls interactions between different sources, such as when using XMLHttpRequest orTags are bound by the same origin policy. These interactions generally fall into three categories:

  1. Cross-origin writes are generally allowed. Examples include links, redirects, and form submission. A small number of HTTP requests require adding preFlight.
  2. Cross-origin embedding is generally allowed such as img SRC, style href and script SRC.
  3. Cross-origin reads are generally not allowed, but can often be cleverly read access with embedded resources. For example, you can read the height and width of an embedded image, call methods of embedded scripts, or availability of an Embedded Resource.
  1. HTTP long and short connections, and how do long connections know if the data is finished

Length of connection

  • A short connection is each time a data connection is established -> data transfer -> closed
  • A long connection is to establish a connection -> transfer data -> keep the connection -> transfer data -> close the connection
  • Advantages: Avoids the overhead of establishing/releasing connections
  • Http1.1 The default setting of Connection:keep-alive indicates that a node-holding Connection is supported

How do I know when the data has been transferred

The short connection closes the connection after sending the requested data, so that the client reads EOF(-1) indicating that the data transfer is complete

  1. content-length
  • As the name implies, its value is the entity length and transmission length, when the two are equal, the data transfer is completed; Only suitable for > the server knows the size of the returned content, such as the client requesting a static page, an image, etc
  1. Transfer-Encoding
  • If it is a dynamic page, the server does not know the content size in advance and transfers the data using transfer-Encoding: chunk mode. That is, data is generated on one side and sent to the client once
  • In the chunk mode, data is sent in chunks, consisting of a series of chunks, ending with a chunk of ‘O’ length
  1. Messages that do not contain a message body (1XX, 304, etc.) end with a blank line
  2. The server closes the connection and determines the length of the message

Common HTTP headers

  1. Connection:
  • Close (tells the WEB server or proxy server to disconnect after completing the response to this request and not to wait for further requests for this connection).
  • Keepalive (tells the WEB server or proxy server to hold the connection until it responds to the request).
  1. Keep-alive: This header indicates how long (in seconds) the WEB server is expected to remain connected if the browser requests to remain connected. For example, keep-alive: 300
  2. Expire, ETAG, cacheControl, last-Modified, if-no-match, if-Modified-since HTTP cache
  3. Content-type: Specifies how the server parses data sent by the client
  • Content-type: application/json For axios, post when axios.post(URL,{a:1,b:2}) and the second argument is an object, the default is this Type
  • Content-type: application/x-www-form-urlencoded For AXIos, let data = {a:1,b:2}; Axios.post (url,qs.stringify({data})), which is the default type when the second argument is a string
  • Content-type: multipart/form-data For axios, let data = new FormData() for post; data.append(‘a’,1′); data.append(‘b’,2); Axios. post(URL,data), which is the default type if the argument is formData, or if the action is submitted using the form itself
  1. Content-length: The WEB server tells the browser the Length of the object it is responding to
  2. Transfer-encoding: The WEB server indicates how it encodes the body of the response message (not the object in the body), such as whether it is chunked. Example: transfer-encoding: chunked
  1. How do you collect requestAnimationFrame execution events and what do you do if a frame is dropped?

I’m going to record the start event, I’m going to record the start event after 100 calls, I’m going to subtract / 100 to get the average time, so I’m going to reduce the interference, but I’m going to collect 100 valid times without taking into account the dropped frames, what is the valid time, The requestIdleCallBack implementation says that this frame is valid and can be collected, so collect 100 frames and figure out the requestAnimationFrame.

  1. Do you know the difference between Target and currentTarget?

Target is the target element that the event fires, and eventTarget is the element that is bound to the event, the parent or ancestor node of the target element

  1. Where do you register react synthetic events? Event broker?

And native event binding

  • React events are not bound to a specific node, but to a document, whereas native events are bound to a specific node
  • Native events (prevent bubbling) prevent the execution of composite events, and composite events (prevent bubbling) do not prevent execution of native events
  • Native events on the node are executed in the target phase, whereas synthesized events are executed in the bubbling phase, so native events are synthesized first and then bubbled to the parent node

Why have your own set of events

  1. Reduce memory consumption, improve performance, don’t need to register so many events, an event type is registered on document only once
  2. Unified specification, solve IE event compatibility problem, simplify event logic
  3. Be developer friendly

What the composite event did for you

  1. A wrapper reat for a nativeEvent uses different synthesized event objects for different event types, which are placed in evet.nativeevent
  2. React doesn’t just handle the event types you declare. It also adds new events, such as onChange, blur, change, click, focus, etc. If you only register a native onChange event, this event can only be triggered if you lose focus.
  1. Compatible handling of events across browsers

Internet Explorer does not have an addeventListener, so it is a safe bet to use attachEvent when registering events without addEventListern

  1. Why 0.1 + 0.2! == 0.3, do you know the principle?

This recommendation to read this article, I just read it, and then I was asked.

  1. React hooks capture Value
  1. The React page is uninstalled

Route redirecting, page refreshing, or page closing causes page uninstallation

How do I display a message box when the page is uninstalled?

A dialog box is displayed when the user switches to the page

Use route guards, but only link tags can be used for page jumps

import {Prompt} from 'react-router-dom';
const Editor=(a)= >{
    return (
        <div>
          <Prompt
            when={true}
            message={location= >'Articles to save roar, sure to leave? '} / ></div>)}Copy the code

A dialog box is displayed when the user closes the page

Listen for the beforeUnload event to prevent the default event from happening first and then a prompt box is displayed

useEffect((a)= > {
    const listener = ev= > {
        ev.preventDefault();
        ev.returnValue='Articles to save roar, sure to leave? ';
    };
    window.addEventListener('beforeunload', listener);
    return (a)= > {
        window.removeEventListener('beforeunload', listener)
    }
}, []);
Copy the code

CSS

  1. CSS counter

Use to write a directory structure:

  1. Define a counter counter-reset:section
  2. Define counter increment: section where you want to add
  3. Display counter(section, ‘.’)
  4. The difference between counters and counters is whether they are displayed nested
<style type="text/css"> #demo1 ol { counter-reset: section; list-style-type: none; } #demo1 ol li { counter-increment: section 1; } #demo1 ol li:before { /* content: counters(section, '.'); */ content: counter(section, upper-roman)' . '; /* content: counter(section, cjk-ideographic) ", "; */ /* content: counter(section, upper-roman) ". "; */ } </style>Copy the code
  1. When does z-index take effect
  1. The z-index attribute applies only to the element that has been located. So if you use z-index on an element that is not located, it will not work.
  2. The cascading effect of elements under the same parent element is affected by the z-index of the parent element. If the z-index value of the parent element is small, then the z-index value of the child element is large
  3. I suggest to practice, the central idea is the above two, my experiment results are as follows:
  • The parent tag position attribute is relative.
  • The problem tag has no position attribute (excluding static).
  • The problem tag contains a float property. Float does not take effect when you have a position property (except static)
  • The z-index value of the ancestor label of the problem label is small
  1. The difference between the property values of position
Attribute values role
absolute Generates an absolutely positioned element relative to the first parent element other than the static positioned element. The position of the element is specified by the “left”, “top”, “right”, and “bottom” attributes.
fixed Generates an absolutely positioned element, positioned relative to the browser window. The position of the element is specified by the “left”, “top”, “right”, and “bottom” attributes.
relative Generates a relatively positioned element that is positioned relative to its normal position. Therefore, “left:20” adds 20 pixels to the left position of the element.
static The default value. Without positioning, the element appears in the normal stream (ignoring the top, bottom, left, right, or Z-index declarations).
sticky Hover after rolling for a while
  • Fixed is fixed relative to the window, regardless of whether the parent container is relative
  • Relative refers to the generation of relative positioning, positioning relative to their normal position, the original position is retained, pro measurement
  1. CSS implements the animation, how do you get it to execute this to execute another keyFrame, how do you know when the animation is finished
  2. Mobile adaptation

This is a popular question, I suggest reading this article, if you don’t have time, can see my summary on GitHub

  1. Out of document flow

This is basic CSS knowledge, if you don’t know, be sure to check it out. This article summarizes it well

  1. Several ways to hide elements in CSS
  1. The display: None element will disappear completely on the page, and the space occupied by the element will be taken up by other elements, which means it will cause the browser to rearrange and redraw. Does not trigger its click event
  2. The difference between visibility: Hidden and display: None is that the space occupied by the element will remain after the page disappears, so it will only cause the browser to redraw, not rearrange. The inability to trigger its click is appropriate for scenarios where the page layout is not expected to change after the element is hidden
  3. After setting opacity to 0, elements are also hidden from the user’s eyes, which is a way to hide elements. One thing in common with Visibility: Hidden is that an element still takes up space after it is hidden, but we all know that when transparency is set to 0, the element is just invisible and remains in the page. Click events can be triggered

HTML

  1. How does innerHTML differ from dangerousSetInnerHTML in React?

The innerHTML reads the value of the string, turns it into an HTML structure, and if the string has a script tag in it, it executes that JAVASCRIPT script. That’s an XSS attack. Also called cross-site scripting attacks dangerouslySetInnerHTML does is not convert directly into your HTML code to prevent XSS attacks. We should take a look at web security. I haven’t summarized it yet, so I’ll write it back.

  1. Will the HMTL in the head show up? There’s something in the head

HTML is really robust, it’s really hard to make an HTML file undisplayable. However, if you put HTML in the header, the browser will move the HTML into the body as you run through the code, squeezing out everything underneath it that was in the head, as shown below. The execution time of the style and script tags in the head was changed.

A picture is worth a thousand words

  1. Security implications of rich text editors

The security implications of a rich text edit box are that the innerHTML is used to display the content. If a Script tag is present in the text, the JS will be executed, a stored XSS attack.

  1. H tag nesting, what is the problem?

Let’s try this out. You can make a guess and run the code below.

<div>
    <h1>I'm only wrapped in h1 and in front<h3>I got h3 and H1 wrapped at the same time</h3>I'm only wrapped in h1, and it's in the back</h1>
</div> 
Copy the code
  1. Img Alt and title attributes

Although simple, but I forgot, you must remember ah. The Alt attribute value is a required attribute that appears at the position of the image when the image does not load properly, and the title value is displayed when the mouse moves over the image

  1. Refluxing and repainting

Browser render page

  1. Browsers can’t read HTML directly; they need to build a DOM tree first
  2. Turn the CSS read into a csSOM that the browser can understand
  3. CSS standardization, such as red -> rGBA font- Weigth :bold becomes numeric
  4. Compute the specific style of the DOM tree
  5. Generate a layout tree, remove what is not displayed, and calculate the information for each element
  6. Generate a hierarchical tree, where pages are layered on top of each other
  7. The composition thread turns the layers of the layered tree into blocks
  8. GPU rasterization turns blocks near Windows into bitmaps, which are rendered at the minimum granularity, and then stored in the GPU process
  9. Once rasterization is complete, the browser goes into the GPU process and pulls out the page content to display on the screen, completing the rendering phase

backflow

Backflow is the layoutTree generated from the concrete style and DOM tree. This step needs to calculate the size and position of each element (ignore the display: None element).

redraw

We convert the layout tree and style to the actual pixels on the screen, which is called the redraw node. Therefore, backflow must lead to repainting, repainting is not necessarily backflow, and the cost of backflow is higher than painting.

Performance optimization

  • The browser itself is optimized, and it maintains a queue for updates, similar to batch optimization. However, if a synchronous layout event is triggered, the browser forces the queue to flush. So we should avoid triggering synchronous layout events. We are familiar with getBoundingClientRect, offsetTop, offsetLeft, offsetWidth, offsetHeight
  • By reducing the number of redraw rearrangements that occur, avoid the following code and use it insteadel.style.cssText += 'border-left: 1px; border-right: 2px; padding: 5px; ', or modify the class name
const el = document.getElementById('test');
el.style.padding = '5px';
el.style.borderLeft = '1px';
el.style.borderRight = '2px';
Copy the code
  • Avoid frequent manipulation of DOM structures and put them in first if necessaryDisplay: noneWait for the DOM operation to finish before releasing the elements (because they don’t appear and trigger a backflow redraw)
  • Elements with complex animation operations use absolute positioning to take them out of the document flow to reduce frequent backflow of parent and subsequent nodes
  • GPU acceleration, which uses CSS to enable CPU acceleration such as transform, opacity, and filters, does not cause backflow redrawing

algorithm

  1. back
  2. Double pointer
  3. Dynamic programming
  4. Binary sort
  5. The tree
  6. Time complexity

In terms of algorithms, interview questions are required, and written questions are required. Above is must master oh. Double pointer look at this article, it is easy to understand, learn to super simple, very efficient.