css

layout

1. Keep a fixed width of 100px in the middle and adapt

  • The position location
  • flexbox
  • calc
  • float

2. Left picture right text, right adaptive width

  • The position location
  • flexbox
    • Flex-grow has a fixed width on the left and a 1 on the right, but the content on the right exceeds the remaining space. Width: 0
  • calc
  • float

3. Fix the footer in the bottom method

  • The position location
  • flexbox
  • calc

4. Set the right border effect inside ul except for the last li.

  • last-child
  • nth-last-of-type
  • not

li:not(:last-child)

5. How to write CSS with more than 2 lines of ellipsis

A single

{
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
Copy the code

Multiple lines

{
  display: -webkit-box;
  word-break: break-all;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3
}
Copy the code

Flex layout

1. Introduce CSS3 flexbox and its common attributes

The purpose of this layout model is to provide a more efficient way to lay out, align, and allocate space among items in a container. In a traditional layout, blocks are arranged vertically from top to bottom. An inline layout is arranged horizontally. The elastic box layout has no such inherent directional constraints and is free to be used by the developer. See juejin. Cn/post / 695178…

Flex: 1 is short for what

The Flex attribute is short for flex-Grow flex-shrink flex-basics

  • Flex-grow (enlarge) claims the remaining space of the parent container. The default value is 0
  • Flex-shrink defines the compression ratio of a child container. The default value is 1
  • Flex -basis or width, then they reserve this amount of space with the parent, and then the parent allocates the remaining space to the container with flex-grow set. If you set both flex-basis and width, the width property is overridden, meaning that flex-basis takes precedence over width. It is important to note that if either flex-basis or width is auto, the non-auto attribute takes precedence.

Flex: 1

   flex-grow: 1;
   flex-shrink: 1;
   flex-basis: 0%;
Copy the code

Flex: None

   flex-grow: 0;
   flex-shrink: 0;
   flex-basis: auto;
Copy the code

Flex: non-negative numbers:

The flex - turns: digital; flex-shrink: 1; flex-basis: 0%Copy the code

3. Flex layout, how to arrange eight elements in two rows

<style>
    .parent {
        width: 100%;
        height: 150px;
        display: flex;
        flex-flow: row wrap;
        align-content: flex-start;
    }
    .child {
        box-sizing: border-box;
        background-color: white;
        flex: 0 0 25%;
        height: 50px;
        border: 1px solid red;
    }
</style>
<div class="parent">
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
</div>
Copy the code

The basic concept

1. Difference between nTH-of-type and nth-child

  • Nth-child: Selects the NTH element of the parent element
  • Nth-of-type: selects the NTH specified element of the parent element

2. The difference between inline and block-level elements

  • Inline elements are arranged on a straight line (the default width is content only), all on the same line, horizontally.
  • Block-level elements occupy one row each (the default width is 100% of its parent container (the same width as the parent element), regardless of the content) and are arranged vertically. Block-level elements start on a new line and end on a line break.
    • Block-level elements can contain inline and block-level elements. Inline elements cannot contain block-level elements, only text or other inline elements.
  • The difference between the attributes of inline elements and those of block-level elements is mainly due to the attributes of the box model: for inline elements, width is invalid, height is invalid (line-height can be set), margin is invalid, padding is invalid

3. The difference between CSS pseudo-classes and pseudo-elements

1) pseudo-classes (pseudo – classes)

  • At its core, it is used to select information outside the DOM tree, elements outside the document that cannot be selected by ordinary selectors, to add some special effects to the selectors.
  • Hover ractive :visited: Link :visited: first-child: Focus :lang, etc
  • Since state changes are non-static, when an element reaches a specific state, it may get a pseudo-class style; When the state changes, it loses the style again.
  • As you can see, it functions somewhat like class, but is based on an abstraction outside of the document, so it is called a pseudo-class.

2) Pseudo-elements

  • The DOM tree has no defined virtual elements
  • The core is that you need to create elements that don’t normally exist in documents,
  • For example ::before ::after selects the content specified by the element and shows the content before or after the element.
  • The content controlled by a pseudo-element is no different from that of an element, but it is an abstraction based on an element and does not exist in the document, so it is called a pseudo-element. Used to add special effects to certain selectors
  • The difference between:
  1. Said method
  • In CSS2, pseudo-classes and pseudo-elements are represented by a single colon:,
  • According to CSS2.1, pseudo-classes are represented by single colons, and pseudo-elements are represented by double colons ::.
    • Browsers also accept the single colon notation for pseudo-elements (:before, :after, :first\ufffeline, : first-letter, etc.) that already existed in the CSS2 era.
  • All new pseudo-elements (such as :: Selection) added after CSS2 should be written with double colons.
  • In CSS3, there is also a difference in syntax between pseudo-classes and pseudo-elements. Pseudo-elements are modified to start with ::. Browsers continue to support pseudo-elements that begin with:, but it is recommended that the specification begin with ::
  1. Define different
  • Pseudo classes are fake classes that can be added to achieve the effect
  • Fake elements are fake elements that need to be added in order to be effective
  1. Conclusion:
  • Both pseudo-classes and pseudo-elements are used to represent elements outside the document tree
  • Pseudo-classes and pseudo-elements are represented by a single colon: and a double colon ::, respectively
  • The key difference between pseudo-classes and pseudo-elements is that without pseudo-elements (or pseudo-classes),
  • Whether an element needs to be added to achieve the effect, if it is, it is a pseudo-element, if it is, it is a pseudo-class.
  1. Similarities:
  • Neither pseudo-classes nor pseudo-elements appear in the source file or DOM tree. There are no pseudo classes or elements in the HTML source file. Differences:
  • Pseudo-classes are simply different forms based on ordinary DOM elements, and they are a feature of DOM elements.
    • Pseudo-elements can create abstract objects that do not exist in the DOM tree and that can be accessed.

4. The difference between link and @import

  1. Link is an XHTML tag that, in addition to loading CSS, can be used to define other transactions such as RSS. @import belongs to CSS and can only load CSS.
  2. When link references CSS, it is loaded at the same time as the page loads. @import requires the page to be loaded after the page is fully loaded. So there will be no CSS style at the beginning of the page, flashing the style (if the Internet is slow)
  3. Link is an XHTML tag with no compatibility issues. ©import was introduced in CSS2.1 and is not supported by older browsers.
  4. Link supports using Javascript to control the DOM to change the sample; At sign 10 to the 011 does not support that.

5. What properties does position have? position: sticky

attribute
  • The static default values
  • Relative does not deviate from the document flow
  • Absolute Is the nearest parent element that is not static and is removed from the document flow
  • Fixed is positioned relative to the browser window and out of the document flow
  • Inherit inherits the position property of the parent element
  • Initial is used to set the CSS property to its default value
  • If the sticky element is set, its position will not be affected by positioning (top and left are invalid) in the screen range. When the element is moved out of the offset range, the positioning will become fixed, and the left and top attributes will become fixed, and the characteristics are as follows:
    1. Do not leave the document flow
    2. When an element is rolled past a specified offset in the container, the element is fixed to the specified position in the container
    3. The fixed relative offset of an element is relative to its nearest ancestor element with a scroll box, and if none of the ancestors can be scrolled, the offset is calculated relative to the viewPort

6. Redraw and reflux (first of all, it is necessary to distinguish between redraw and reflux definitions, and finally to ask for details of specific optimization, so as to understand the candidates not only clearly distinguish the definition, but also clearly distinguish the purpose of daily work optimization)

define
  • redraw
    Changing the color attribute of an element does not retrigger the layout (that is, it does not trigger backflow), but does trigger style calculation and drawing
  • backflow
    When you change the size and position of an element, you re-style the layout drawing and all the rest of the process
The specific properties
  • backflow
    Width, height, line-height, padding, margin, diaplay, border, top, position, float, font-size, overflow
  • redraw
    Color, background, background-size, visibility, box-shadow

To optimize the

  • ClassName: Do not use JS code to style multiple DOM elements. Use a className instead
  • Transform: transform instead of top, left, margin-top, margin-left… These displacement properties
  • Don’t get DOM inside a loop: Don’t get DOM styles inside a loop such as offsetWidth, offsetHeight, clientWidth, clientHeight, etc. The browser has a backflow buffer, and backflow occurs when these properties are fetched
  • Document flow: Remove multiple reflow elements from document flow, such as animations, using the fixed or absolute value of the position property
  • Change together (modify all attributes that need to be changed at the same time)
  • Avoid table layouts
  • Avoid USING CSS expressions

7. Difference between transform and position: Absolute top:50

  1. Location:
    • Using top left positioning directly changes the actual position of the element. Simply put, you top: 5px, which is really 5px above or 5px away from the top of the parent container.
    • Using transform: translateY(-5px) just changes the visual position, the element itself is still in 0px, but is visually shifted 5px upwards. This is very important for CSS layout, because most of the time you don’t want an element animating (for example, flying away from the fade off) causing the parent element to change size and then the siblings element to change position causing the collective shaking. So a lot of times we use transform.
  2. Grammar:
    • Transform is relatively convenient when making effects, because the perspective of transform is the element itself, so it is more intuitive. If you want an element to fly 50px to the left, that’s transform: translateX(-50px),
    • With both left and parent elements position: absolute, you might write left from left: 100px to left: 30px, which is not intuitive.
  3. Efficiency:
    • Transform is more efficient than Top Left because it doesn’t change the CSS layout and because the rendering behavior is mostly in the element itself. Also, in earlier versions, forcing hardware acceleration with transform: translateZ(0px) seemed to apply only to transform

8. What color is the following div

<style>
  div {
    color: red;
  }
  #title {
    color: yellow;
  }
  div.title {
    color: bule;
  }
</style>
<div class="title" id="title">abc</div>
Copy the code

9. What are the ways to optimize and improve performance of the CSS?

  • Avoid over-constraining
  • Avoid descendant selectors
  • Avoid chain selectors
  • Use compact syntax
  • Avoid unnecessary namespaces
  • Avoid unnecessary repetition
  • It is best to use semantic names. A good class name should describe what it is, not what it looks like
  • Avoid!!! Important, you can select other selectors
  • Simplify rules as much as possible. You can combine duplicate rules from different classes

10. Differences and advantages of SSR and CSR

  1. SSR: server-side rendering, the content on the page is generated by the browser server directly display the HTML returned by the server can be
  2. CSR: Client rendering. The content on the page is the JS file we loaded. The rendered JS file runs on the browser and the server only returns an HTML template
  3. Common server-side rendering frameworks: React based Next-js and VUE based nuxt.js
  4. Differences between the two (PROS and cons of CSR)
    • CSR (client rendering) TTFP time (first screen time) is long
    • CSR is not SEO friendly because Baidu crawlers (most crawlers) only recognize HTML content, not JS content
    • In CSR, the front end is responsible for page rendering and the back end is responsible for data processing, thus realizing the separation of the front end and the back end and each performing its own duties
    • SSR can affect server performance

11. Advantages and disadvantages of SPA architecture

  1. What is SPA?
  • The full name is single page application.
  • A SPA is a WEB application that requires resources (HTML, CSS, JS, etc.) to be loaded in a single request, i.e. dynamically loaded without refreshing.
  • The term “single page” is used because pages are never reloaded and refreshed after initial loading.
  1. advantages
  • Reduce stress on the server side.
  • Improved page rendering.
  • Due to the popularity of mobile devices, web services can be developed to provide data in JSON format, which can then be provided for use by different clients.
  • SPA use, we can use an HTTP API, an HTTP API compared to render an HTML page in the server side has many advantages, so it can be very convenient for unit testing and other operations, but also can be used by many other client programs.
  1. disadvantages
  • The first screen takes a long time to load.
  • SEO is not friendly.

12. Optimized first screen rendering

  • Optimize the first screen loading, reduce the white screen time, improve the loading performance:
  • Speed up or reduce HTTP request wear: Use CDN to load public library, use strong cache and negotiated cache, use domain name convergence, use Base64 for small pictures, use Get request instead of Post request, set access-Control-max-age to reduce precheck request, When jumping to other domain names or requesting resources of other domain names within the page, use the browser Prefetch for preparsing.
  • Lazy loading: lazy loading of non-important libraries, non-first-screen pictures, lazy loading of SPA components, etc.
  • Reduce the volume of requested content: enable server Gzip compression, JS and CSS file compression and merger, reduce the size of cookies, SSR directly output rendered HTML, etc.
  • Browser rendering principle: optimize key rendering paths to reduce JS and CSS blocking rendering as much as possible;
  • Optimize user waiting experience: use loading progress bar, loading diagram, skeleton screen instead of blank screen;

js

Cross domain

  1. Cross domain method
  • jsonp
  • Forward proxy: CORS: Access-Control-allow-origin The front-end directly requests domain names
  • The HTTP proxy, HTTP proxy – middleware
  • proxy
  • postMessage
  • nginx add_header Access-Control-Allow-Origin “*”
  1. In cross-domain cases, sometimes sending a POST request will see an options request. Why?
  • In cross-domain request, it can be divided into simple request (GET and partial POST, when post, content-type belongs to Application/X-ww-form-urlencoded, multipart/form-data, text/plain) and complex request. An Options request appears before a complex request is issued. The foreground cross-domain POST request, due to the existence of the Cross Origin Resource Share (CORS) specification, the browser will first send an Options sniffing, and the header with Origin to determine whether the cross-domain request permission. The server responds to the value of Access Control Allow Origin for the browser to match origin, and if it does, formally sends a POST request. What is an options request? It is a probing request in which the client can decide what action is necessary for a specific resource or know the performance of the server before making a specific resource request.

Strong and negotiated caching

There are two types of browser cache: strong cache (also known as local cache) and negotiated cache.

  • When a browser requests a resource, it first obtains the header information of the resource cache to determine whether the strong cache (cache-control and Expires information) is matched. If a match is matched, the browser directly obtains the resource information, including the header information, from the cache. This request does not communicate with the server at all; Under Firebug you can view information returned from a strongly cached resource, such as a strongly cached JS file viewed by local Firebug
  • If the strong cache is not hit, the browser sends a request to the server with the header fields returned from the first request (last-modified/if-modified-since and Etag/ if-none-match). According to the relevant header information in the request, the server compares whether the result is negotiated cache hit. If a match is made, the server returns a new response header that updates the corresponding header in the cache, but does not return the resource content, which tells the browser that it can be retrieved directly from the cache; Otherwise, the latest resource content is returned

Talk about the entire WebPack life cycle

  • Initialization parameter
    • Read and merge parameters from configuration files and shell statements to arrive at the final parameters
  • Begin to compile
    • Initialize the Compiler object with the parameters obtained in the previous step, load all configured plug-ins, and execute the corresponding run method to start compiling
  • Determine the entrance
    • Locate all entry files according to the entry in the configuration
  • Compile the module
    • Starting from the entry file, call all configured Loader to compile the module, find the module that the module depends on, and then recurse this step until all the entry dependent files are processed in this step
  • Complete module compilation
    • After compiling all modules using Loader in Step 4, we get the final translated content of each module and the dependencies between them
  • Output resources
    • According to the dependency relationship between the entry and modules, the chunk is assembled one by one containing multiple modules, and then each chunk is converted into a separate file and added to the output list. This step is the last chance to modify the output content
  • Output complete
    • After determining the output content, determine the output path and file name based on the configuration, and write the file content to the file system

In the above process, Webpack will broadcast a specific event at a specific point in time, the plug-in will execute the specific logic after listening for the event of interest, and the plug-in can call the Api provided by Webpack to change the execution result of Webpack

The webPack build process

Webpack csS-loader and style-loader, file-loader and URl-loader

  • CSS – loader and style – loader
    • Css-loader processes CSS files
    • Style-loader packages the style file code imported from the JS import into the JS file. When running the JS file, the style will be automatically inserted into the style tag
  • File – loader and url – loader
    • File-loader returns the URL of the image
    • Url-loader can process images based on the limit attribute. When the size of an image is smaller than limit (byte), the image is transferred to Base64. When the size is larger than limit, the image is processed by filie-loader.
    • Url-loader encapsulates file-loader, but url-loader does not depend on file-loader

What optimization webpack has done, development efficiency, packaging strategy and so on

  1. To optimize the speed
  • Using a higher version of Webpack (using WebPack 4)
  • Multi-threaded/multi-instance builds: Thread-loader
  • Shrink the packaging scope
    • Exclude /include (confirm loader rule scope)
  • Make full use of cache to improve secondary build speed

-DLL – Use DLLPlugin for subcontracting, use

What are the common loaders? What problems do they solve?

  • Babel-loader: convert ES6 to ES5;

  • Css-loader: loads the CSS and supports modularization, compression, and file import.

  • Style-loader: inserts CSS code into JS and loads CSS through DOM operations.

  • Eslint-loader: checks js code through ESLint;

  • Image-loader: loads and compresses images at night;

  • File-loader: To export files to a folder and reference the output file through a relative URL in the code;

  • Url-loader: similar to file-loader, the content of a file can be base64 injected into the code when the file is small.

  • Source-map-loader: loads additional source map files for debugging.

cdn

  1. What is the
  • Content delivery network
  • A geographically dispersed network of servers that store web site caches as servers and client entities
  • Subsequent requests can be delivered to the original server without requiring any further requests, ensuring that the pressure on critical servers is reduced and that web pages are accessed at the same speed by users worldwide
  1. advantages
  • Resolving Network Congestion
  • Speed up your site by caching your content on edge servers and serving up what you’re looking for first
  • Improved network performance ensures a better user experience
  • Improve SEO for better ranking
  1. disadvantages
  • This IP appeared under hundreds of websites, SEO weight scattered
  • costly
  • Only static content can be accelerated

V8 garbage collection mechanism

Garbage collection: Clean up data that is no longer used in memory to free up memory space. V8 divides memory into new generation space and old generation space.

  • Cenozoic space: used for short-lived objects
    • It is divided into two Spaces: from space and to space
    • Scavenge: Initiate the GC algorithm when the FROM space is filled
      • Surviving objects are moved from From space to space
      • To empty the from space
      • From space is exchanged with to space
      • Complete a Cenozoic GC
  • Old generation space: Used for objects that live for a long time
    • Conditions of transition from Cenozoic space to old age space
      • Be the subject of the Scavenge Avenge on at least one occasion
      • When to space volume exceeds 25%
    • Mark clearing algorithm: mark alive objects, unmarked objects are released
      • Incremental flags: small module flags, held between code executions, where GC affects performance
      • Concurrent markup (latest technology): does not block JS execution
    • Compression algorithm: the fragmentation object caused by clearing in memory is moved to one end of the memory heap to solve the fragmentation of memory

New a constructor that does something inside; What if the constructor actively returns a value?

  1. Creates a new empty object in memory
  2. Let this point to the new object
  3. Execute the code inside the constructor to add properties and methods to the new object
  4. Return the new object (so no return is needed inside the constructor)

The return primitive type will return an empty object and the return object type will return that object

Inheritance way

  1. Class inheritance
  2. Constructor inheritance
    • The call method can change the execution context of a function, so calling the constructor of the parent class in a subclass is equivalent to calling the constructor of the parent class in a subclass’s this, but eventually returns to the object created by the subclass, implementing the operation of the subclass calling the constructor
  3. Combination of inheritance
    • While instance attributes do not affect the reference properties of class attributes, constructors that execute the parent class in the subclass constructor can all pass parameters
  4. Prototype inheritance
    • proptotype
  5. Parasitic combinatorial inheritance
    • Directly copy the prototype of the parent class to the subclass, and change the constructor of the prototype of the parent class into the constructor of the subclass. The object that becomes a subclass is inherited, generally mixed with other constructor inheritance

for.. In and object. keys

for.. The in loop returns all enumerable properties that can be accessed through the object, both in the instance and in the stereotype. Keys () is used to get all the enumerable property values of the Object itself, but not the properties in the prototype, and then return an array of property names for.. In enumerates enumerable properties on the Object prototype chain, object.keys does not

The paper eventLoop

The execution result
setTimeout(function() { 
     console.log(1) 
}, 0); 

new Promise(function(resolve, reject) { 
     console.log(2) 
     for (var i = 0; i < 10000; i++) { 
          if(i === 10) {console.log(10)} 
          i == 9999 && resolve(); 
     } 
     console.log(3) 
}).then(function() { 
     console.log(4) 
})  
console.log(5)      // 2 10  3  5 4 1
Copy the code

Introduce the principle, difference and application scenarios of throttling and anti-shake

  1. Stabilization:
  • Principle: The callback is executed after the event is triggered for n seconds. If the event is triggered again within n seconds, the timer is reset
  • Scene:
    • Button Submission: Prevents multiple submission of the button and only performs the last submission
    • Search box association: prevents association from sending a request and only sends the last input
  1. Throttling:
  • Principle: Specifies that only one function can be triggered in a unit of time. If more than one function is fired in this unit of time, only one function will take effect.
  • Scene:
    • Drag scenario: Perform this operation only once within a fixed period to prevent uHF position changes
    • Zoom scenario: Monitor browser resize

Common methods for arrays

forEach map filter some every reduce find some every reduce

Code execution results

Data type if([] == false){console.log(1)}; if({} == false) {console.log(2)}; if([]){console.log(3)}; if([1] == [1]){console.log(4)}; / / 1 3Copy the code
The variable name raises alert(a); a(); var a = 3; function a() { alert(10); } alert(a); a = 6; a(); // 'function a(){ alert(10) }'' 10 3 typeError: a is not a functionCopy the code
Arrow function this var name = 'window'; var A = { name: 'A', sayHello: () => { console.log(this.name) } } A.sayHello(); A.sayHello.call({name: 'B'}); // window // windowCopy the code
For (var I =1; i<=5; i++) { setTimeout(function timer() { console.log(i); }, i*1000); } // for (var I =1; i<=5; i++) { (function(j) { setTimeout(function timer() { console.log(j); }, j*1000); })(i); } for (let i=1; i<=5; i++) { setTimeout(function timer() { console.log(i); }, i*1000); }Copy the code

Determine the data type

Object.prototype.toString.call(a).slice(8, -1);
Copy the code

Function execution procedure

  1. Determine the execution environment
  • When JavaScript executes global code, it creates a global execution context (there is only one global execution context for the lifetime of the page). When a function is called, its execution context (execution environment) is created. What manages multiple execution contexts is the call stack (which is a data structure used to manage the relationship between function calls)
  1. Create a stage
  • Before the function is executed, some initialization is done, which is called the create stage. This stage is mainly used to generate variable objects, establish the scope chain, and determine the this point in preparation for the subsequent execution stage.
  1. Execution phase
  • Once everything is ready, the code execution phase completes variable assignments, function references, and other code execution.
  1. The garbage collection
  • When the function completes execution, it fades out of the call stack, is destroyed, and waits for the browser’s garbage collection.

What is event delegation, its principle, function and disadvantage

  • In simple terms, events are onclick, onMousemove and so on. Delegation is to delegate your work to someone else and let someone else do it.
  • How it works: With event bubbling, only one event handler is designated to manage all events of a certain type.
  • Purpose: Reduce DOM operations, save memory space, and improve performance.
  • disadvantages
  1. Event delegation is based on bubbling, and non-bubbling events are not supported
  2. Too many layers, bubble process may be blocked by the middle layer
  3. If you use event delegates for all events, you can expect event miscalculations, meaning that events that should not trigger are bound

What about front-end error monitoring

  • Front-end errors can be classified as immediate runtime errors (code errors) and resource loading errors.
    • How to catch real-time errors:
  1. The try… catch

  2. window.onerror

    • Catch resource loading errors:
  3. Object.onerror () (cannot bubble)

  4. performance.getEntries()

  5. Error event capture

    • Extension: Cross-domain JS runtime errors cross-domain catch?

You can.

  1. Add the Crossorigin attribute to the script tag

  2. Access-control-allow-origin :* Sets the js resource response header access-Control-allow-origin :*

    • Basic principles for error reporting:
  3. Using ajax

  4. Working with Image objects (for production use)

component

vue

1. Vue response type principle

DefineProperty initializes Vue by default, redefines attributes in data with Object.defineProperty, and adds get set methods for attributes. When the property is obtained in the template, get is called, followed by dependency collection. Set is executed when a property changes, notifying the dependent to distribute the update.

2. How do arrays detect changes

  • The hijack detects changes by modifying the array prototype chain and overriding the array method.
  • Change array attribute __proto__ to our own set of methods, currently we refer to the blocking of push pop unshift shift sort splice resolve seven methods
  • Each item in the loop array is observed only if it’s an object type

3. Why does data in a component have to be a function and then return an object, while data in a new Vue instance can be an object

Because components are used for reuse, using the same constructor, JS objects are reference relationships, so there is no scope isolation, and the root new Vue instance, is not reused, so there is no reference object problem

4. Implementation principle of Vue. nextTick

NextTick It is an asynchronous method. It mainly includes four methods: Promise, MutationObserve, setImmediate, setTimeout, and EventLoop JS. After the synchronization task is complete, the micro task is performed, followed by the macro task. So Promise takes precedence.

5. Communication between Vue components

Props, $emit, vuex

6. Vuex principle

Vuex implements a one-way data flow, with data stored globally in a State. When a component wants to change data in the State, it must do so through Mutation, which also provides a subscriber pattern for external plug-in calls to obtain updates of State data. However, when all asynchronous operations (common in calling back-end interfaces to get updated data asynchronously) or batch synchronous operations need Action, but the Action cannot directly modify the State, and the State data still needs to be modified by Mutation. Finally, render to the view as the State changes.

7. Why is virtual DOM fast

  • There are so many properties in the real DOM, plus frequent dom manipulation, that every change needs to be replaced in rendering.
  • Virtual DOM He uses JS objects to describe a DOM structure, and compares the new and old nodes with each DOM change, and uses DOM diff algorithm.
  • The same children will not be re-rendered, existing ones will be replaced, and non-existing ones will be added

8. DOM DIFF

  • First sibling comparison, then child node comparison
  • First judge one side has a son, one side does not have a son, add or delete
  • Both have sons
  • Recursively compare sons

react

Handwritten code

1. Single-linked list inversion

var list = {
  val: 1,
  next: {
    val: 2,
    next: {
      val: 3,
      next: {
        val: 4,
        next: null
      }
    }
  }
}
Copy the code

recursive

function invertList (head) { if (! head || ! head.next) return head const currenttList = invertList(head.next) head.next.next = head head.next = null return currenttList } const result = invertList(list) console.log(result)Copy the code

non-recursive

function invertList (head) { if (! head || ! head.next) return head let currentList = null while (head ! = null ) { let temp = head.next head.next = currentList currentList = head head = temp } return currentList } const result = invertList(list) console.log(result)Copy the code

2. Given an array, the parentId and ID of each element in the array are used to determine the parent-child relationship and parse it into a tree structure

[{id, children: []}] [{id: 0}, {id: 1, parentId: 0}, {id:2, parentId: 0}, {id: 3, parentId: 0}, {id: 11,parentId: 1}, {id: 111,parentId: 11}...]

3. Write a deep copy by hand

function deepClone(origin) {
  if (getType(origin) === 'Array') {
    return origin.map(item => deepClone(item));
  }

  if (getType(origin) === 'Object') {
    const obj = {};
    Object.keys(origin).forEach(key => (obj[key] = deepClone(origin[key])));
    return obj;
  }

  return origin;
}
Copy the code

4. Enter a string to output all substring abcd a B C D AB ABC abcd BC BCD c CD

getStr(str) { for (let i = 0; i <= str.length; i++) { for (let j = 0; j <= str.length - i; j++) { if (str.substr(i, j)) { console.log(str.substr(i, j)); }}}}Copy the code

5. Transform multidimensional array to one-dimensional or expand n layers according to parameters

const arr = [1, [2, 22], [3, [33, [333]]],[4, [44, [444, [4444]]]], [5, [55, [555, [5555, [55555]]]]]]

const flatteOne = (arr) => { let res = [] arr.forEach(item => { res = Array.isArray(item) ? [...res,...item] : [...res, item] }) return res; } const flatte = (arr, num = 0) => { if(! num) { return arr; } let newArr = arr for(let i = 1; i <= num; i++) { newArr = flatteOne(newArr) } return newArr }Copy the code

6. Implement formatting output eg 88888888888 888888888

7. To find the intersection of two array elements,4,5,6,9,10 [1] [6] output,4,5,6 [1]

Implement a json.stringify

if (!window.JSON) {
  window.JSON = {
    parse: function (sJSON) {
      return eval("(" + sJSON + ")");
    },
    stringify: (function () {
      var toString = Object.prototype.toString;
      var isArray =
        Array.isArray ||
        function (a) {
          return toString.call(a) === "[object Array]";
        };
      var escMap = {
        '"': '\\"',
        "\\": "\\\\",
        "\b": "\\b",
        "\f": "\\f",
        "\n": "\\n",
        "\r": "\\r",
        "\t": "\\t",
      };
      var escFunc = function (m) {
        return (
          escMap[m] ||
          "\\u" + (m.charCodeAt(0) + 0x10000).toString(16).substr(1)
        );
      };
      var escRE = /[\\"\u0000-\u001F\u2028\u2029]/g;
      return function stringify(value) {
        if (value == null) {
          return "null";
        } else if (typeof value === "number") {
          return isFinite(value) ? value.toString() : "null";
        } else if (typeof value === "boolean") {
          return value.toString();
        } else if (typeof value === "object") {
          if (typeof value.toJSON === "function") {
            return stringify(value.toJSON());
          } else if (isArray(value)) {
            var res = "[";
            for (var i = 0; i < value.length; i++)
              res += (i ? ", " : "") + stringify(value[i]);
            return res + "]";
          } else if (toString.call(value) === "[object Object]") {
            var tmp = [];
            for (var k in value) {
              if (value.hasOwnProperty(k))
                tmp.push(stringify(k) + ": " + stringify(value[k]));
            }
            return "{" + tmp.join(", ") + "}";
          }
        }
        return '"' + value.toString().replace(escRE, escFunc) + '"';
      };
    })(),
  };
}
Copy the code

Given a string ‘asdasdfaffjasaso’, return the first unrepeated letter

Methods a

var str = 'asdasdfaffjasaso'; var strs = []; var len = str.length; var num = 0; for (var i = 0; i < len; i++) { strs.push(str.slice(i, i + 1)); } for (var j = 0; j < len; j++) { for (var k = 0; k < len; k++) { if (j ! = k) { if (strs[j] ! = strs[k]) { num++; } } } if (num == len - 1) { console.log(strs[j]); break; } num = 0; }Copy the code

Method 2

var firstUniqChar = function(s) { let stack = {} for(let i=0; i<s.length; i++){ if(! stack[s[i]]){ stack[s[i]] = 1 }else{ stack[s[i]]++ } } let ret = -1; for(let j=0; j<s.length; j++){ if(stack[s[j]]==1){ ret = j return ret } } return ret };Copy the code