preface

Check the missing, check the missing, you don’t know where the missing, how to fill the missing? Because this article has more than 10,000 words, it is a little long, so I suggest you can look at my interview [check] to find out where you [missed], and then come back to [fill in] (Tencent, Baidu, Xiaomi, netease, etc.)

This article is a summary of my interview questions and solutions some time ago. In fact, I did not want to continue to write about the interview questions, because there are many such articles in the community, but if every place to turn over, and it is not convenient to review, so I decided to write this article for their own consolidation

HTML5

1. The new features

  • Semantic labels

  • Enhanced forms

    • New form attributes:placehodler.autofocus.multiple.required.minlength.maxlength.max.min.pattern
  • Video and Audio

    • HTML5Provides a standard for playing audio files, i.e. using<audio>.<video>The element
  • Canvas drawing

    • Labels are just containers for graphics that must be drawn using scripts
  • SVG drawing

  • HTML5 Geolocation is used to locate a user’s location

  • Drag and drop API

    • ondragstart: Triggers action on a dragged element when the element begins to be dragged
    • ondragenter: An event that is triggered when a drag element enters a target element
    • ondragover: An event that is triggered when a drag element is moved on the target element, acting on the target element
    • ondragleave: Triggered when a drag element is dragged away from the target element
    • ondrop: An event triggered by the mouse release of the dragged element over the target element, acting on the target element
    • ondragend: An event that is triggered when the drag is complete, acting on the dragged element
  • WebWorker

    • The HTML5 specification provides a multi-threaded solution, and this is itWebWorker (WebWorker learning reference article)
  • WebStorage(this platitudes, will not expand)

  • WebSocket

    • HTML5 is the first to provide a protocol for full duplex communication over a single TCP connection.

CSS

1. The CSS selector

Several common CSS selector priorities are:! Important > Inline > ID selector > Class selector > Tag selector > General selector

  • The ID selector
  • Class selectors
  • Label selector
  • Descendant element selector
    • Action: Selects the specified descendant element of the specified element. Syntax: Ancestor element descendant element {} (separated by space)
  • Child element selector
    • Action: Selects the specified child element that specifies the parent element. Syntax: parent element > child element
  • pseudo-classes
    • A pseudo-class represents a particular state of an element
    • :activeAdd styles to the activated elements
    • :focusAdds styles to elements that have keyboard input focus
    • :hoverAdd styles to elements when the mouse hovers over them
    • :linkAdd styles to links that are not accessed
    • :visitedAdds styles to links that have been accessed. (Privacy issues can only be set to color)
    • :first-childAdds a style to the first child of the element
    • :langDirection band designationlangAttribute to the element add style
    • ::selectionMatches portions that are selected or highlighted by the user
  • Pseudo elements
    • : pseudo-elements represent special locations within an element
    • :first-letterAdds a special style to the first letter of the text.
    • :first-lineAdds a special style to the first line of text.
    • :beforeAdd content before the element.
    • :afterAdd content after the element
  • Other child element selectors
    • :first-childSpecifies the first element in the parent element and the style of the specified element

2. How do I clear floats

  • Adds height to the parent element of the float element
  • Add the last redundant element to the last child element and set itclear:both, so you can clear the float
  • Pseudo-element removal (handwrittenclearfix )
.clearfix:after {
    content: ' ';
    display: block;
    clear: both;
}
Copy the code
  • For the parent elementoverflow:hidden

3. Difference between EM and REM

  • emThis is the font size relative to the parent element, which must be recalculated when the font size of the parent element changes
  • remOnly relative to the root directory, the HTML element. There are theremThis unit, we just need to adjust the root elementhtmlthefont-sizeYou can achieve dynamic fit of all the elements

4. Redraw and Reflux (rearrangement)

Redrawing does not necessarily lead to backflow, backflow does lead to redrawing

  • Backflow: When we make changes to the DOM that result in a change in the DOM’s geometry (such as changing the width or height of an element, or hiding an element), the browser recalculates the element’s geometry (which also affects the geometry and position of other elements), and then draws the calculated results. This process is called reflux (also known as rearrangement)

    • Most expensive operation: Changing the geometry of a DOM element
    • “Affordable” operation: Change the DOM tree structure
    • The most overlooked operation: getting the value of some particular property. When you use properties like this:offsetTop,offsetLeft,offsetWidth,offsetHeight,scrollTop,scrollLeft,scrollWidth,scrollHeight,clientTop,clientLeft,clientWidth,clientHeight
  • Redraw: When we make changes to the DOM that result in a style change without affecting its geometry (such as changing the color or background color), the browser doesn’t have to recalculate the element’s geometry and simply draw a new style for the element (skipping the backflow shown above). This process is called redrawing

5. Position Sticky positioning

Sticky positioning (it is recommended to understand based on specific practice, some interviewers will dig deep)

  • Sticky positioning Sticky positioning sticky positioning sticky positioning

  • position: sticky; Location based on the user’s scrolling position

  • Sticky positioning elements are dependent on user scrolling, switching between position:relative and position:fixed

  • It behaves like position:relative; When the page scrolls beyond the target area, it behaves like Position: Fixed; It will be fixed in the target position

  • Element positioning is represented by relative positioning before crossing a specific threshold, and then fixed positioning

  • This specific threshold refers to one of top, right, bottom or left, in other words, to specify one of the four thresholds of top, right, bottom or left for sticky positioning to take effect. Otherwise it behaves the same as relative positioning

6. Display: none and visibility: hidden

display:none

  • If you set it to an elementdisplay: none, the element and all its descendants are hidden, which is the most frequently used method of hiding by front-end developers. Hidden elements cannot be clicked, cannot be accessed by auxiliary devices such as screen readers, and the occupied space disappears

visibility: hidden

  • Setting elementsvisibility: hiddenYou can hide this element, but the hidden element still takes up the same space as the unhidden element, meaning that the element is invisible but still affects the layout of the page

7. What is the difference between style before and after body

  • It is written before the body tag to facilitate gradual rendering by the browser
  • Written after the body tag: Because the browser parses the HTML document line by line, parsing to the style sheet written at the end (either inline or in the style tag) causes the browser to stop rendering before loading and re-rendering after parsing the style sheet

8. Principle of Flex implementation

  • A question I was asked in an interview was what I thought was the underlying principle of Flex, but so far I haven’t been able to find any information on it. (Or maybe I misunderstood, did the interviewer just want me to talk about their containers, properties, etc.?) Welcome to dig friends comment section

9. The difference between standard box model and IE box model

  • The width of the IE box model is border + padding + content

10. Z-index failure scenario

The concept of cascading context, and the priority of cascading order, cascading level (for details, please refer to thoroughly understand CSS cascading context, cascading level, cascading order, z-index)

  • Stacked context: Stacking context is a three-dimensional concept in HTML. In the CSS2.1 specification, the position of each box model is three-dimensional, namely the X axis, Y axis and the Z axis representing the cascade on the flat canvas respectively. In general, elements are laid out along the X and Y axes on the page, and we don’t notice their overlapping relationships on the Z axis. Once the elements are stacked, you can see that one element may overwrite another or be overwritten by another

  • Hierarchy: In the same hierarchy context, this describes the z-axis order that defines the hierarchy context elements in that hierarchy context

  • How to generate “Cascading context”

    • The root element in HTML itself j has a cascading context, called “root cascading context”
    • The normal element sets position to a non-static value and z-index to a specific value, generating a cascading context
    • New properties in CSS3 can also generate cascading contexts
  • Cascade order: Arrange according to the following figure

11.CSSOM generates rules

Build CSSOM (CSS Object Model – CSS Object Model)

  • The process of building a CSSOM is very similar to the process of building a DOM. When the browser receives a piece of CSS, the first thing the browser does is recognize the Token, then build the node and generate the CSSOM (the rules are as follows)
  • BytescharacterstokensnodesCSSOM

JS

Var, let, const

1.1 var

  • varDeclared variables do not have block scope
  • varDeclared global variables are automatically changed towindowObject properties
  • varDeclared variables are promoted (declarations are advanced, but assignments are not, and will still be reportedundefinedFault)
  • varDeclared variables can be declared repeatedly in the same scope, whileletconstIs not allowed, otherwise an error is reported

1.2 the let and const

  • letThe command is used to declare variables and its usage is similar tovar, but the declared variable, only inletThe command is valid in the code block
  • constDeclare a read-only constant. Once declared, the value of a constant cannot be changed
  • Temporary dead zone
    • ES6 explicitly states that if there are let and const commands in a block, the variables declared by the block to those commands form a closed scope from the start. Any time these variables are used before declaration, an error is reported
    var tmp = 123;
    if (true) {
      tmp = 'abc'; / / ReferenceError error
      let tmp;
    }
    Copy the code

2. Differences between assignment, deep copy, and shallow copy

  • When we assign an object to a new variable, we assign the object’s address on the stack, not the data in the heap. That is, two objects point to the same storage space. If any object is changed, it is the content of the changed storage space. Therefore, the two objects are linked.

  • Shallow copy: The basic data types of objects before and after the copy do not affect each other. However, the reference types of objects before and after the copy do affect each other because they share the same memory block.

  • Deep copy: creates a new area of heap memory to store the new object, and makes a recursive copy of the child objects in the object. The two objects before and after the copy do not affect each other

3. Arrow function

  • Syntax is more concise and clear. As you can see from the basic syntax example of the arrow function above, the definition of the arrow function is much more concise, clear, and fast than the ordinary function definition

  • The arrow function has no prototype, so the arrow function itself has no this

  • The arrow function does not have its own this. The arrow function’s this refers to the this inherited from the first normal function in the outer layer when it is defined (note: defined, not called). So, the orientation of this in the arrow function is determined when it is defined and never changes

  • 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 have no arguments objects of their own. Calling Arguments in the arrow function actually gets the value in the outer local (function) execution environment

4. Apply, call, bind

4.1 in common

  • All three are used to change the context of a function, that is, to changethisPoint to the

4.2 the difference between

  • bindInstead of calling immediately, it returns a bound new function. Usage scenarios: do not need to point to immediately, but like generating a new function to bind a function to an object for use
let newFn = fn.bind(this.Obj)
newFn(arg1,arg2,arg3...)
Copy the code
  • call,applyAll are called immediately
    • applyThis is called immediately, and returns the result of the function’s execution. This refers to the first argument, and the second argument is an array containing the parameters of the fn function.fn.apply(this.Obj,[arg1,arg2,...] )). Usage scenario: If there are many parameters to pass, you can use an array to call the parameters
    • callThis is called immediately, and returns the result of the function’s execution. This refers to the first argument, which can be followed by multiple arguments, and these are arguments to the fn function.fn.call(this.Obj,arg1,arg2...)). Usage scenario: This parameter can be used if there are not many parameters to be passed

5. Various API methods for arrays and characters

5.1 an array

  • Create an array

    • Array() let arr = new Array()
    • [] let arr = []
    • Array.of()An Array of (1, 2, 3) / / [1, 2, 3]
  • Detection array

    • Array.isArray(value)
  • Conversion method:

    • toLocaleString()
    • toString()
    •   let colors = ['red'.'yellow'.'blue'];
        console.log(colors.toString()) // red,blue,green
        console.log(colors.toLocaleString()) // red,blue,green
      Copy the code
  • The stack method:

    • push()Returns the length of the array after adding an element to the end of the array
    • pop()Removes the last item from the end of the array (modifying the array), reduces the array length, and returns the deleted item
  • Queue method:

    • shift()Removes the first item in the array (modifying the original array) and returns the item
    • unshift()Adds any element to the front of the array and returns the length of the array
  • Array manipulation methods:

    • Reverse () reverses the array (modifying the original array) and returns the sorted array

    • By default, sort() sorts the items in ascending order, calls the toString() method on each item, and then compares the resulting strings to determine how to sort them (modifying the original array). You can also accept a function. The resorted array

    • Concat () is used to connect two or more array arrayObjects. concat(arrayX,arrayX,…… ArrayX), creates a copy of the current array, appends the parameters received to the end of the copy, and returns the newly constructed array (without modifying the original array)

    • Slice () creates a new array based on one or more items in the current array, taking one or two arguments, both the start and end positions returned (without changing the original array)

    • Splice () specifies the start position of the first argument, deletes several of the second argument, and inserts any item for the third argument. Splice returns an array of deleted items, or null (delete, insert, replace) (modify the array)

    • Fill () This method takes the given value and fills an array (modifying the original array)

     ['a'.'b'.'c'].fill(7)
     / / (7, 7, 7)
     new Array(3).fill(7)
     / / (7, 7, 7)
    Copy the code

    You can also receive second and third parameters that specify the start and end positions of the fill

     ['a'.'b'.'c'].fill(7.1.2)
     // ['a', 7, 'c']
    Copy the code
    • flat()Used to “flatten” a nested array into an array and return a new array. Receives a parameter indicating the number of layers you want to flatten (Do not change the original array)
  • Check the location method:

    • indexOf().lastIndexOf()
      • indexOf()andlastIndexOf()Both receive two parameters: the item to look for and the index representing the starting point of the search.indexOfMethod starts at the head of the array,lastIndexOfMethod starts at the end of the array. If not found, return- 1
    • findIndex()Returns the position of the first qualified array member not found, returns -1, with two arguments: each item handler and (optionally) the scope object on which the function is run
    [1.5.10.15].findIndex(function(value, index, arr) {// The current value, the current position, and the original array
     	return value > 9;
    }) / / 2
    Copy the code
  • Value checking method:

    • find()Finds the first eligible array member, taking two arguments: a function that iterates through each item and (optionally) the scope object that runs the function
    [1.4, -5.10].find((n) = > n < 0) / / - 5
    Copy the code
    • includes()Returns a Boolean value that takes two arguments: the item to look for and the index representing the starting point of the search
  • Iterative method:

    • Every runs the given function on each item in the array, returning true if the function returns true for each item, and false otherwise.

    • Some, as opposed to some, is a function that only returns true for an item in the array (false for all errors, true for all otherwise)

    • Filter Returns a new array of items that match the filter (without changing the original array)

    let number = [1.2.3.4.5];
     let filterResult = number.filter((item, index, array) = >{
         return item > 2
     })
    console.log(filterResult)/ / [3, 4, 5]
    Copy the code
    • ForEach it simply runs the passed function on each item in the array. No return value (traversing the array, modifying the array)

    • Map returns a new array, each of which is the result of running a function on the corresponding item in the original array (without changing the original array)

    let number = [1.2.3.4.5];
     let mapResult = number.map((item, index, array) = >{
         return item * 2
     })
    console.log(mapResult)// [2, 4, 6, 8, 10]
    Copy the code

6. Methods for traversing objects

  • for inPrimarily used to iterate over enumerable properties of an object, including properties that are owned and inherited from the stereotype
var obj = {"name":"tom"."sex":"male"}

Object.defineProperty(obj, "age", {value:"18".enumerable:false})
// Add the non-enumerable attribute age

Object.prototype.protoPer1 = function(){console.log("name is tom"); }// Add attributes to a function through the prototype chain

Object.prototype.protoPer2 = 2 // Add attributes through the prototype chain to an integer value of 2

for(var a in obj){
	console.log(a)
    console.log(obj[a])
}
// The age attribute in the example is not enumerable, so there is no output
Copy the code
  • Object.keysThis method returns an array of the object’s own enumerable attributes
// (the above code is an example)
console.log(Object.keys(obj))
//	["name","sex"]
Copy the code
  • Object.getOwnPropertyThis method is used to return the object’s own properties, including enumerable andAn enumerationThe properties of the
// (the above code is an example)
console.log(Object.getOwnPropertyNames(obj))
//	["name","sex","age"]
Copy the code

7. Common new features of Es6

  • ES6 Class
  • for… Of and the for… in
  • Object deconstruction
  • Rest/Spread operators
  • Template string
  • const let
  • promise
  • Async function
  • Module

8. Differences between Set, Map, WeakSet and WeakMap

Please refer to Ruan Yifeng’s ECMAScript 6 Introduction to Set and Map data structures

  • Set ES6 provides a new data structure called Set. It is similar to an array, but the values of the members are unique and there are no duplicate values

  • A Map is a data structure used to access key-value pairs. A key can only correspond to one value and the key cannot be repeated

  • WeakSet structure is similar to Set, which is a collection of non-repeating values

    • WeakSet members can only be objects, not other values
    • WeakSet objects are weak references, that is, garbage collection mechanism does not consider WeakSet’s reference to the object, that is, if other objects no longer reference the object. Then the garbage collection mechanism will automatically input the amount of memory occupied by the object, regardless of the existence of the object and WeakSet
  • WeakMap structure is similar to Map structure and is also used to generate a set of key-value pairs

    • WeakMap only accepts objects as key names (except null) and does not accept values of other types as key names
    • The object to which the key name of WeakMap points is not included in the garbage collection mechanism

9. Understanding of prototype and prototype chain

For example, C language has classes to achieve inheritance, Java can achieve inheritance through abstract classes, and JS in order to abstract out a class of things, so that the same class of things can have the same attributes and methods, they will be the prototype chain as the main way to achieve inheritance. In terms of data structure, a prototype chain is actually a linked list. The instance has a pointer to the prototype, and the prototype contains a pointer to the constructor

10. Stages of the browser event flow and three parameters that the event listens for

DOM event propagation consists of three stages:

  • 1. Capture stage
  • 2. The target object invokes the event handler
  • 3. Bubble stage

The third argument, true, goes to the capture phase, false goes to the bubble phase. Capture cannot be cancelled, but bubbling can. The binding event defaults to the bubbling phase

11. Closure usage issues

Because closures cause variables in functions to be stored in memory, which can be very memory consuming, you should not abuse closures, which can cause performance problems for web pages and memory leaks in IE. The solution is to remove all unused local variables before exiting the function

12. How do I clear closures

The implication of a closure is that a function can access the scope that the function can access when it is called, for example, when function A is defined, a can access variable B. Each function has its own closure, which also resides in memory when the function is not garbage collected. Unneeded functions are reclaimed if closures need to be cleared. According to the JavaScript reclamation mechanism, a memory space is reclaimed when there are no variables to point to. The closure is cleared by assigning the unwanted function name to NULL

The framework

1. Why is vue’s data a method

  • If data is an object in a component, then the scope is not isolated. The data property values in the subcomponent will affect each other. If the data option in a component is a function, then each instance can maintain an independent copy of the returned object. Data property values between component instances do not affect each other; The instance of new Vue is not reused, so there is no object reference problem

  • When a component is reused multiple times, multiple instances are created. Essentially, these instances all use the same constructor. If data is an object, the object is a reference type that affects all instances. So to ensure that data does not conflict between different instances of the component, data must be a function

2. Communication problems between VUE components

General parent-child component, grandparent component value transfer, Vuex should be able to answer, but can you answer more clearly and comprehensively? This may impress the interviewer (see article). How many do you know?

3. Watch monitor implementation

Briefly explain the principle (for details, please check the official source code) :vmcall$watchAfter, the first callobserveFunction createsObserverExample observation data,ObserverAnd createDep , DepUsed to maintain subscribers. Then create aWatcherInstance to provideupdateFunction. As soon as the data changes, the callback function is executed layer by layer

4. Hash and history modes of vue-router

4.1 the hash pattern

Hash mode, originally used to control the position of the page window with anchor points, has the following characteristics:

  • In hash mode, all page hops are performed by the client, making it more flexible for page interception. However, each URL change is not an HTTP request, so it is not conducive to SEO optimization

  • Hash mode is a mode that concatenates the path of the front-end route with a hash sign (#) after the real URL. When the path after the hash # changes, the browser does not re-initiate the request, but rather fires the Hashchange event.

  • You can change the URL, but it does not trigger a page reload (the hash change is logged in window.hisotry) and therefore is not an HTTP request, so this pattern is not conducive to SEO optimization

  • You can only change the part after #, so you can only jump to the URL of the same document as the current URL

  • Urls can only be changed by strings

  • Use window.onhashchange to listen for changes to the hash to implement a refresh free jump

4.2 the history mode

History mode, according to Mozilla Develop Network, calling history.pushState() has the following advantages over modifying hash directly

  • The History API is a new feature in H5 that allows developers to directly change the front-end routing by updating the browser URL address without re-initiating the request

  • The new URL can be any URL of the same origin as the current URL, or it can be the same as the current URL, but this will record a repeat operation on the stack

  • The stateObject parameter allows you to add any type of data to a record

  • Additional title attribute can be set for subsequent use

  • The pushState and replaceState commands enable this function

  • It is not as compatible with hash and requires server support, otherwise the page will be 404 when refreshed

  • In history mode, history.pushState is used to realize the page without refreshing. This way, the URL change is an HTTP request, so it will request the server again. This also makes it necessary to configure the address on the server, otherwise the server will return 404. To ensure this, it is best to configure 404 pages in the project

5. Vue3 Proxy is different from vue2 defineProperty

5.1 defineProperty shortcomings

  • Cannot detect the addition or removal of object attributes, for which we need to useVue.setVue.deleteTo ensure that the response system is operating as expected
  • Cannot monitor array subscript and array length changes, when the array index is directly set value or change the array length, cannot respond in real time
  • Performance issues. When there is a lot of data in the data and the hierarchy is very deep, the performance will degrade because all the data in the data must be traversed and set to be responsive

5.2 Comparison and Difference

  • Object.definePropertyOnly the attributes of the object can be hijacked. New attributes need to be manually addedObserveAnd theProxyIs a direct proxy object
  • whyProxyCan you solve the above pain points? The fundamental reason is thatProxyIs an object with a built-in interceptor that all external access must pass through first. Access to both previously defined and newly added attributes will be intercepted (proxySee Ruan Yifeng’s ES6 tutorial for detailsProxy)

6.Com Puted is different from Watch

6.1 concept

  • computed: evaluates attributes, depends on other attribute values, andcomputedThe value of is cached, and only the attribute values it depends on change the next time it is retrievedcomputedIs recalculatedcomputedThe value of the
  • watch: is more of a “watch” function, similar to some listening callbacks for data, which are executed for subsequent operations whenever the listening data changes

6.2 the difference between

  • The same:computedandwatchBoth listen to/rely on a piece of data and process it
  • Different: They are bothvueThe implementation of the listener is justcomputedMainly used for synchronous data processing,watchIs mainly used to observe the change of a value to complete a section of expensive complex business logic. Can be usedcomputedIs a prioritycomputedTo avoid multiple calls when multiple data affect one datawatchEmbarrassing situation

7. During which lifecycle the asynchronous request is invoked

You can call hook functions created, beforeMount, and Mounted because in these three hook functions, data is already created and can be assigned to the data returned by the server. However, I recommend calling an asynchronous request from a Created hook function because it has the following advantages

  • In this way, data from the server can be obtained more quickly, reducing the loading time of the page
  • SSR is not supportedbeforeMountmountedHook function, so putcreatedTo help consistency

Virtual DOM. 8

8.1 What are the benefits of the virtual DOM?

  • Assuming that there are 10 DOM updates in one operation, the virtual DOM does not immediately manipulate the DOM, but instead updates the DOM for those 10 updatesdiffThe content is saved to a local JS object, which is eventually used onceattchtoDOMTree, and then the subsequent operation, to avoid a lot of unnecessary calculation. Therefore, the advantage of using JS objects to simulate DOM nodes is that the update of the page can be reflected in the virtual DOM first, and the speed of operating JS objects in memory is obviously faster. After the update is completed, the final JS object is mapped to the real DOM, which is submitted to the browser to draw

8.2 Through the DIFF algorithm comparison operation JS object to achieve the difference update

  • If no old node exists, a new node is created and the parent node is inserted.
  • If there is no new node, the old node is destroyed.
  • If the node changes, usereplaceChildChanging Node Information
  • If the node does not change, it compares the child nodes of the node and makes a recursive call

8.3 Actual rendering rules of the virtual DOM

Vue template/ React JSX -> render function -> generate vnodes -> compare old and new VNode diff algorithms when there are changes, and actually update the real DOM

9. Vue3 new features

  • Composition API(Look at the picture to solve the problem that the developer jumps up and down repeatedly when finishing or reading the code, and the code of the same function is not aggregated.)
    • Use highlights: The entire function is a function; The function contains the data and logic to rely on to create a new folder; Function completely independent, function can be reused

  • Say goodbye to$set
    • That’s what I mentioned aboveProxyThe method of data bidirectional binding is rewritten to solve the pain point problem
  • Fragments
    • In short, vuE3 components officially support the declaration of multiple root nodes. In other words, the following is possible. This also means that the render function can also return arraysattribute
  • Vue3.0Will thetsx,class componentWait for better support
  • destroyedRename the life cycle tounmounted
  • beforeDestroyRename the life cycle tobeforeUnmount

10. Vue’s seven methods for overriding arrays

10.1 an overview of the

Vue monitor Array three steps (just a general principle, please check the official source code for understanding or check some authoritative books on Vue source code)

  • Step 1: Get the prototype method of the native Array first, because we still need the native method to implement the Array change after interception
  • Step 2: Use the Array prototype methodObject.definePropertyDo some interception
  • Step 3: Point the Array type data prototype that needs to be intercepted to the modified prototype

10.2 Overriding array methods

Push (), pop(), shift(), unshift(), splice(), sort(), reverse()

11. Vue/react

11.1 similarities

  • These are all componentized development ideas
  • Both support server-side rendering
  • All useVirtual DOM, componentized development, passedpropsParameter for father and son component data transfer, are implementedwebComponentspecification
  • Data-driven view
  • Have a supportnativeReactReact native, Vueweex
  • React has redux, Vue has its own Vuex (adaptive Vue)

11.2 the difference between

  • React is strictly for the VIEW layer of MVC, whereas Vue is the MVVM pattern
  • Unlike Virtual DOM, VUE tracks the dependencies of each component and does not need to re-render the entire component tree. With React, all components will be rerendered whenever the state of the application is changed, so React will require itshouldComponentUpdateThis lifecycle function method is used to control
  • React recommends writing components differentlyJSX + inline style, that is, theHTMLandCSSAll written intoJavaScriptA, that is,all in js; Here’s what Vue recommendswebpack+vue-loadeSingle-file component format, i.ehtml.css.jsWrite it in the same file
  • Data binding: VUE implements two-way data binding, react data flows are one-way
  • stateThe React object is immutable and needs to be usedsetStateMethod update status; invue,stateObjects are not required; data isdataProperties are managed in vUE objects;

12.keep-alive

  • Keep-alive is a built-in component of vue.js.<keep-alive>When dynamic components are wrapped, inactive component instances are cached rather than destroyed. It does not render a DOM element on its own, nor does it appear in the parent component chain. When the component in<keep-alive>The inside is switched, it’sactivateddeactivatedThe two lifecycle hook functions will be executed accordingly. It providesincludewithexcludeTwo properties that allow the component to cache conditionally

13.vuex

13.1 VUEX Core:

  • state: storagestoreThe various states of
  • mutationChange:storeThe state can only be passedmutationmethods
  • action: Asynchronous operation method
  • module: modular
  • getter: is equivalent to calculating attributes, filtering out some values

13.2 vuex use

  • At the heart of every Vuex application is the Store. A “store” is basically a container that contains most of the states in your app. Vuex differs from a purely global object in two ways:

  • Vuex’s state storage is reactive. When the Vue component reads the state from the Store, if the state in the store changes, the corresponding component is updated efficiently accordingly.

  • You can’t just change the state in the store. The only way to change the state in a store is to commit mutation explicitly. This allows us to easily track each state change, which allows us to implement tools that help us better understand our application

Computer network

1. The DNS

DNS (abbreviation of Domain Name System) is used to find IP addresses based on Domain names

1.1 DNS Resolution Sequence

  • localhostsfile
  • localDNSThe cache
  • DNSServer cache
  • DNSServer recursive lookup

1.2 DNS Record Types

When we buy a domain name in Aliyun, we can configure our host domain name resolution rules, that is, record common DNS record types as follows

  • A: Address Record (Address), returns the IP address to which the domain name refers
  • NS: DNS server records (Name Server), returns the address of the server where the next-level domain name information is stored. The record can only be set to a domain name, not an IP address
  • MX: Mail records (Mail eXchange), returns the address of the server that received the E-mail
  • CNAME: Specification name record (Canonical Name), returns another domain name, that is, the current query domain name is a jump to another domain name
  • PTR: Reverse query records (Pointer Record) is only used to query domain names from IP addresses

1.3 DNS Recursive Lookup

Tlab.cloud.tencent.com. 600 IN A 193.112.230.97

  • Ask for the root domain name to get the top-level domain name.comNS(Name Server)A(Address).NSIs the name of the top-level domain,AnamelyNSCorresponding IP address
  • Ask for a top-level domain name to get a secondary domain name.tencnet.comNSA
  • Ask for a secondary domain name to get a tertiary domain name.cloud.tencent.comNS andA
  • Ask for a level 3 domain name to get a level 4 domain name.tlab.cloud.tencent.comNS andA
  • Finally, thetlab.cloud.tencent.comThe IP address is returned to the user and cached
  • The user obtains the real IP address and caches it

2.Http1 vs. Http2

HTTP / 1.1 2.1 faults

  • Queue Head blocking

    • Although HTTP/1.1 protocol can send multiple requests on the same TCP connection, but the multiple requests are sequential, the first request must be processed before the response to the next request. If the first request is particularly slow, all subsequent requests need to be queued.
  • TCP connection number limit

    • A browser can create a maximum of six to eight TCP connections for a domain name. If ten requests are sent to a page at the same time, the next two to four requests can only be sent after the first six to eight requests are returned. How does that work? Domain name sharding comes into being. This eliminates the limitation by allocating resources to different domains (which can be secondary subdomains), but it also doesn’t work by abusing domain sharding because each TCP connection is time-consuming.
  • The Header content is extensive, sometimes exceeding the response content, and many fields are repeated each time.

  • HTTP/1.1 is a text protocol transport and is not secure enough

2.2 New features of HTTP2 compared to HTTP/1.1 include:

  • MultiPlexing, single long connection, binary format transmission, request priority setting

  • Header compression

  • The Server pushes Server Push

3. The difference between Http and Https

Key differences between HTTPS and HTTP (additional layer of SSL or TSL)

  • 1. HTTPS requires a ca to apply for a certificate. Generally, there are few free certificates, so some fees are required

  • 2. HTTP is a hypertext transmission protocol, and information is transmitted in plain text. HTTPS is a secure SSL encryption transmission protocol

  • 3. HTTP and HTTPS use completely different connections and use different ports, the former 80 and the latter 443

  • 4. HTTP connections are simple and stateless; HTTPS is a network protocol that uses SSL and HTTP to encrypt transmission and authenticate identity. It is more secure than HTTP

4. Negotiation cache is different from strong cache

  • Similarities: If a match is hit, the resource is loaded from the client cache, not from the server
  • Difference: The strong cache does not send requests to the server. The negotiated cache sends requests to the server
  • For details, please refer to my previous article (⑥ Front-end basics — Performance optimization, Web security, Linux Common commands).

5. Get and POST

  • GET request parameters are retained in browser history, while parameters in POST are not

  • The GET argument is passed through the URL, and the POST is placed in the Request body. GET is less secure than POST because parameters are exposed directly to the URL and therefore cannot be used to pass sensitive information

  • GET is used to GET information, POST is used to modify data on the server (generally follow this rule)

  • Graphical HTTP illustrates the difference between the two

    • GET: Is used to request access to resources identified by the URI
    • POST: the body used to transport the entity (POSTwithGETThe function is similar, butPOSTIs not the main purpose of getting the corresponding body content.

6. The difference between Cookie and Session

  • Cookie data is stored on the client’s browser (client) and session data is stored on the server, but the session implementation of the server is dependent on the cookie of the client

  • Cookies are not very secure. Others can analyze cookies stored locally and cheat cookies. For security, session should be used

  • 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

  • The limit for a single cookie on the client side is 4K, which means that a site cannot store more than 4K cookies on the client side

7. Use AXIos to add a single field to each request header

Using axios request interceptors, axios. Interceptors. Request. Use

conclusion

The next time I will write an interview related article may be the spring recruitment, which is also my DDL of the 21st class of students. Because the interview found that some problems dig will answer was very vague, investigate its fundamental is not enough because they read the book, many concepts without a cognitive, a man who knows the table, the (in this article a lot of solution is the same, if you only look at these concepts briefly, then when you interview, once the interviewer dig, so you don’t answer, I suggest you take some time to read books and official documents. Therefore, I will read books during my internship to improve my entire knowledge system. I may also write some articles about knowledge in books.

At the end of the article

If you think my writing is good, you can give me a thumbs up. If there is anything wrong or bad, please comment and point it out so that I can correct it

Other articles

  • How to Pass the first stage of the Interview
  • Personal Learning Process (Learning route)
  • ⑥ — Performance optimization, Web security, common Linux commands
  • 5. Front-end basics — Http, Ajax, cross-domain
  • Front end basics ④ – events and DOM
  • ③ Asynchronous (Interview scenario)
  • Front End Basics ② — Scopes and closures
  • Front end basic knowledge ① — CSS interview questions