JS part

1. Write a method that takes two arguments, k and an unordered array of pure numbers. This method returns the KTH largest number in the array when executed. In particular, if you have two digits of the same value in an array, you rank them in the same order. In [3,1,3,2,5,4,5], the first largest number is 5, the second largest number is 4, and the fifth largest number is 1.

  • This topic examines the common basic manipulation of arrays. The idea is to sort the internal values of the array first. After sorting, we need to reverse the array from large to small. Finally, the array is reprocessed and the answer is returned. The implementation code is as follows:
function getNum(k, arr) {            
    let res = arr.sort((a,b) = >b-a);   // Convert an array to a set
    let set = new Set(res);  // Return the class array to the array
    let newArr = Array.from(set);        
    if (typeof newArr[k-1]! = ="undefined") { // Return the found data
        return newArr[k-1];  
    } else {            // No data exclusion error found
        throw Error("No corresponding data found"); }}let arr = [];    
let res = getNum(1, arr);    
Copy the code

2.protoHow does prototype relate?

  • All objects have the proto attribute. In addition to the proto attribute, this special object function also has the unique prototype attribute. The Prototype object has two default properties, the constructor property and the __proto__ property. The prototype attribute adds shareable (inherited) methods and attributes to functions and objects, and __proto__ is a prototype chain of ways to find a function or object. Constructor, which contains a pointer to the original constructor.

3. Call (),.apply().bind() How does the bind method work?

  • Call, apply, and bind change the context in which a function is executed. The difference lies in the call method and parameter passing. Details are as follows:
function fn(. args) {        
fn(1.2);  // The fn function defaults this to the window object
let obj = {        
fn.call(obj,1.2);  // this will become the obj passed in, args will become [1,2];
fn.apply(obj,[1.2]); // This becomes obj passed in, and the argument passed in must be an array;
fn.bind(obj)(1.2); // This will also become the obj passed in. Bind is not called immediately and needs to be called once
Copy the code

Call, apply, and bind can all change the “this” reference. The difference is that the parameters are passed differently. Call and apply are called immediately, but bind is not immediately executed.

  • Bind is implemented as follows
Function.prototype.myBind = function (context) {   
    // Determine whether the calling object is a function
    if (typeof this! = ="function") {     
        throw new TypeError("Error");   
     }   // Get parameters
    var args = [...arguments].slice(1);    
    fn = this;   
    return function Fn() {     
    // Different binding values are passed in depending on how the call is made
        return fn.apply(this instanceof Fn ? newfn(... arguments) : context, args.concat(... arguments)); }}Copy the code

4. What are the basic data types in JS? Do you know what to pack?

  • Boolean null undefined number string symbol Undefined number is a value, so there is no method to call such as undefined.split(“”); So why are calls like “ABC”.split(“”) allowed? The reason is that there will be wrapped objects in JS, which will wrap the string into an object and then call some methods under the object. After the method call is completed, the object will be destroyed, thus completing the function call function of the basic data type.

5. What are macro tasks? What are microtasks?

  • Microtask: A function that needs to be executed asynchronously, after the completion of the main function but before the completion of the current macro task.
  • Macro task: the time granularity of macro task is relatively large, and the time interval of execution cannot be precisely controlled, which does not meet the requirements of high real-time performance.

Common microtasks:

  1. Promise.then
  2. MutaionObserver
  3. Object. Observe (obsolete; Proxy object substitution)
  4. Rocess. NextTick (Node. Js)

Common macro tasks:

  1. Script (can be understood as the outer synchronization code)
  2. setTimeout/setInterval  
  3. The UI rendering/UI events
  4. PostMessage, MessageChannel
  5. SetImmediate, I/O (Node.js)

6.Promise. AllSettled? Make a Promise. AllSettled?

function MyallSettled(list){
    let resArr = new Array(list.length);
    let num = 0;
    return new Promise(resolve= > {            
        list.forEach((item,key) = > {               
            let obj = {};                
            item.then(res= >{                    
                obj['status'] = "fulfilled";                    
                obj.value = res;                    
                resArr[key]= obj;         
            }},err= >{                  
                obj['status'] = "rejected";                    
                obj.reson = err;                    
                resArr[key] = obj;                    
                if(num===list.length){ resolve(resArr); }})})}); }Copy the code

6. Do you understand design patterns in JS? Implement a single example pattern?

let CreateSinge = (function() {
    let instance;
    return function(name) {
        if(instance) {
            return instance;
        return instance = new Single();

let Single = function(name) {
    this.name = name;

Single.prototype.getName = function(){
let getName  = new CreateSinge('getName');
let getDom = new CreateSinge('getDom');
Copy the code

7. What does the virtual DOM do and how to build it?

 class Vdom{
     constructor(option) {
         this.tagName = option.tagName;
         this.props = option.props || {};
         this.children = opton.children || {};
     render() {
         let el = document.createElement(this.tagName);
         for(let propsKay in this.props) {
         if (Array.isArray(this.children)) {
             this.chidren.forEach((item) = > {
         } else {
                 el.innerText = this.children;
         returnel; }}Copy the code

8. Meta viewport

<! DOCTYPE html> <! --H5 standard declaration, using HTML5 doctype, case insensitive --> <head lang= "en" > <! <meta charset= 'utF-8' > <! <meta HTTP-equiv = "x-UA-compatible" content= "IE=edge, Chrome =1" /> <meta http-equiv= "x-UA-Compatible" content= "IE=edge, Chrome =1" <meta name= "description" content= "no more than 150 characters" /> <! <meta name= "keywords" content= "" /> <! <meta name= "author" content= "name, [email protected]" /> <! <meta name= "robots" content= "index,follow" /> <! <meta name= "viewport" content= "initial-scale=1, maximum-scale=3, minimum-scale=1, user-scalable=no" > <! <meta name= "apple-mobile-web-app-title" content= "title" > <! --iOS devices begin--> <meta name= "Apple-mobile-web-app-capable" content= "yes" /> <! -- Title added to the home screen (new in iOS 6) Whether to enable WebApp full-screen mode, <meta name= "apple-itunes-app" content= "app-id=myAppStoreID, affiliate-data=myAffiliateData, affiliate- name=" apple-itunes-app "content=" app-id=myAppStoreID, affiliate-data=myAffiliateData, affiliate- App - argument = myURL "> <! <meta name= "apple-mobile-web-app-status-bar-style" content= "black" /> <meta name= "format-detection" content= "telphone=no, email=no" /> <! <meta name= "renderer" content= "webkit" > <! <meta HTTP-equiv = "x-UA-compatible" content= "IE=edge" > <meta HTTP-equiv = "x-UA-compatible" content= "IE=edge" > <meta http-equiv= "cache-control" content= "no-siteapp" /> <! <meta name= "HandheldFriendly" content= "true" > <! <meta Name = "MobileOptimized" Content = "320" > <! <meta Name = "screen-orientation" content= "portrait" > <! <meta Name = "x5-orientation" Content = "portrait" > <! <meta name= "full-screen" content= "yes" > <! --> <meta name= "x5-fullscreen" content= "true" > <! <meta name= "browserMode" content= "application" > <! - UC application pattern -- -- > < meta name = "x5 - page - mode" content = "app" > <! <meta name= "msApplication-tap-highlight" content= "no" > <! <meta http-equiv= "pragma" content= "no-cache" > <meta http-equiv= "cache-control" The content = "no - cache" > < meta HTTP - equiv expires "content =" 0 "> ="Copy the code

9. There are a large number of pictures on a page (large e-commerce website), and the loading is very slow. What methods do you have to optimize the loading of these pictures to give users a better experience?

  • Image lazy loading, you can add a scrolling event in the invisible area of the page to judge the distance between the image position and the top of the browser and the distance between the page, if the former is less than the latter, the first loading.
  • If it is a slide, album, etc., you can use the image preloading technology to download the first and last images of the current display.
  • If the image is CSS image, you can use CSSsprite, SVGsprite, Iconfont, Base64 and other technologies.
  • If the image is too large, you can use a specially encoded image that will load with a particularly compressed thumbnail to improve the user experience.
  • If the image display area is smaller than the actual size of the image, compress the image on the server based on service requirements. The compressed image size is the same as that on the display.

Vue part

1. What are the communication modes between components in VUE?

  • 1. Prop and $emit are suitable for parent-child component communication. This method is the basis of Vue component communication.
  • Ref: if used on a normal DOM element, the reference refers to the DOM element. If used on a child component, the reference refers to the component instance parent/parent /parent /children:
  • EventBus (emit/emit /emit /on) uses an empty Vue instance/as the central EventBus (event center) to trigger events and listen for events, thus enabling communication between any component, including parent, sibling, or parent components.
  • 4.
    a t t r s / attrs/
    Listeners are suitable for intergenerational component communication
    a t t r s : contains the parent scope p r o p The identification of ( And get ) Feature binding of ( c l a s s and s t y l e With the exception of ) . When a component does not declare any p r o p This contains all the bindings of the parent scope ( c l a s s and s t y l e With the exception of ) And can pass v b i n d = Attrs: Contains feature bindings (except class and style) in parent scopes that are not recognized (and retrieved) by prop. When a component does not declare any prop, it contains all parent-scoped bindings (except class and style), and can be done by v-bind=”
    Attrs “is passed to the internal component. Often used in conjunction with the inheritAttrs option.$listeners: contains a V-ON event listener in the parent scope (without the.native modifier). It can be passed into internal components via V-on = “$Listeners”
  • 5. Provide/inject This function is applicable to descendant components communication ancestor components provide variables through Provider, and descendant components inject variables through Inject. The Provide/Inject API mainly solves the communication problem between cross-level components, but it mainly uses sub-components to obtain the state of the parent components, and establishes a relationship between proactive provision and dependency injection among cross-level components.
  • Vuex is a state management mode developed specifically for vue.js applications. 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’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. The only way to change the state in a store is to commit mutation explicitly. This allows us to easily track each state change.

What is the difference between V-show and V-if in vue?

  • V-show simply switches between display: None and display: block. Whatever the initial conditions are will be rendered, just switch CSS later, and the DOM will remain.
  • V -if is used to talk about Vue low-level compilation. When the property is initially false, the component is not rendered until the condition is true and the condition is switched to trigger the destruction/mount of the component, and this lazy rendering mechanism based on V-IF allows the component to be rendered only when necessary, reducing the initial rendering overhead for the entire page.

3. What does keep-alive do

  • If you need to save the state of some components to prevent multiple renders when switching between components, you can wrap the components that need to be saved with the keep-alive component.
  • The Keep-Alive component has two unique lifecycle hook functions, activated and deactivated. Components wrapped with keep-alive are not destroyed during switching, but cached in memory and executed by deactivated hook function. After hitting the cache rendering, the actived hook function is executed.

4. What about vUE lifecycle hook functions?

  • BeforeCreate: For this variable, watcher events are not available for both data and methods.
  • Created allows manipulation of data and methods in vUE instances, but not yet “DOM” nodes.
  • BeforeMounte: Called before the mount begins: The related render function is called for the first time
  • Mounted: The DOM node is displayed in a document. Operations that require the DOM can be performed only after the DOM node is mounted
  • BeforeUpdate: Data is updated but the page view has not responded to changes. – Updated: Both data and view are updated
  • BeforeDestroy: Events, instructions, etc. are available on the instance before destruction, where the component is not really destroyed.
  • Destroyed: data, instruction, etc. are destroyed completely

5. Is there any difference between computed and Watch in Vue?

  • Computed is a property that relies on other properties to compute values, and computed values are cached and returned only when computed values change.
  • Watch listens for a change in the value and executes a callback, in which logical operations can be performed.

The difference between mixins and mixins

  • Mixins are used for global mixins that affect each component instance and are typically initialized this way by plug-ins
    beforeCreate() {
        / /... logic
        // This approach affects the beforeCreate hook function for each component}})Copy the code

7. Diff algorithm for vue 2.x and Vue3.x renderers

  • Peer comparison, and then child node comparison

  • First determine if one parent has children and one parent has no children (if the new child has no children, remove the old child)

  • Compare the case where both nodes have children (core diff)

  • Recursively compare child nodes

  • Normally, the time complexity of the two Diff trees is O(n^3), but in practice, we rarely move the DOM across hierarchies, so Vue optimizates the Diff from O(N ^3) -> O(n). Only when the old and new children have multiple children nodes, the core Diff algorithm is needed to compare them at the same level.

  • The core Diff algorithm of Vue2 adopts the algorithm of double-end comparison, which starts from the two ends of the old and new children, finds the reusable node with the help of key value, and then carries out relevant operations. Compared with the React Diff algorithm, it can reduce the number of nodes to be moved, reduce unnecessary performance loss, and be more elegant

  • The type of VNode is determined when VNode is created, and the bit operation is used to determine the type of a VNode in the process of mount/patch. On this basis, combined with the core Diff algorithm, the performance is improved compared with Vue2

  • While the documentation doesn’t recommend using mixins directly in your applications, it’s helpful if you don’t abuse them, such as globally mixing packaged Ajax or utility functions.

  • Mixins are probably the most common way to extend components. If multiple components have the same business logic, it can be stripped out and mixed into code through mixins, such as pull-up and pull-down data loading logic.

  • It is also important to note that mixins incorporate hook functions that are executed before the component’s own hook functions, and are selectively merged when they encounter options with the same name

The react part

1. What are the communication modes between React components?

  1. Parent to Child: In React, when a parent component calls a child component, it can add the data to the properties of the child component. The child component receives the data through the props property. This is the parent component communicating with the child component.
  2. React is a one-way data flow. Data can only be transmitted from top to bottom. When a child component has data that needs to be communicated to the parent, it needs to define a callback in the parent and pass the callback to the child component, which then calls the callback method passed by the parent to communicate.
  3. Communication across components – context. Using the Context API, you can pass information from a component to its descendants.

2. How to implement lazy route loading in React?

  • React 16 adds the lazy method, which makes lazy loading of components easy. Lazy loading of routes can also be implemented by combining routing components with lazy
 import {Route} from "react-router-dom";  
 import React,{Suspense} from 'react';       
 const HomeView = React.lazy(() = >import("./home"));     
 function App(){          
     return <div>              
     <h1>Route lazy loading</h1>              
     <Route path="/" exact render={()= >{                    
         return <Suspense fallback={<div>The placeholder content before component Loading is loaded</div>} ><HomeView />              
     </Suspense>}} / ></div>       
 export default App;
Copy the code
  • In the code above, we introduced a dynamic component using lazy and then put the component into the root route. This way, the component will load dynamically only when the user visits the front page of the site. In Suspense, lazy and Suspense must be used together in the React specification. Dynamic components introduced by lazy must be put into Suspense. The Suspense fallback attribute is the placeholder for lazy components before they are loaded.

3. What are the life cycle functions of React?

  1. Constructor: Initialize the component, initialize the state of the component, etc.
  2. Static getDerivedStateFromProps() : This function is used to map information in props to state.
  3. Render: Generates the virtual DOM
  4. ComponentDidMount: componentDidMount completes by handling the side effects update phase in this function:
  5. static getDerivedStateFromProps()
  6. ShouldComponentUpdate () : This lifecycle function is used to determine whether component updates should be made.
  7. GetSnapshotBeforeUpdate () : The component has completed diff and is about to update the real DOM. The user takes the last DOM snapshot. This function must be used with componentDidUpdate, and the return value becomes the third parameter componentDidUpdate.
  8. ComponentDidUpdate () : When component updates are complete, side effects are usually handled in this function. About to be unmounted: componentWillUnmount: A component is about to be unmounted and is used to remove data or events added to the global component.

5. React performance optimization is a periodic function

  • ShouldComponentUpdate is used to determine if the DOM needs to be repainted by calling the Render method. Because dom rendering is very performance consuming, if we can write a more optimized DOM diff algorithm in shouldComponentUpdate method, we can greatly improve performance

6. I now have a button that I want to bind to the react button.

class Demo {

  onClick = (e) = > {
    alert('I clicked the button.')}render() {
    return <button onClick={this.onClick}>button</button>
Copy the code

7. How do sibling nodes react to each other? That’s when the key is different

  • ReactNode is an array with a map and then a ReactNode is returned. To facilitate optimization within React, we must add a key to each ReactNode. The key prop is not intended for developers, but for React. React updates only the properties of the reactNode if the key is the same or if the component properties change. If the key is different, react destroys the component and then recreates it

8. In the mobile application implemented by React, what are the optimization solutions to consider if there is a lag

  1. Add a shouldComponentUpdate hook to compare the old and new props, prevent updates if the values are the same, avoid unnecessary rendering, or use PureReactComponent instead of Component. The shallow comparison logic shouldComponentUpdate has been encapsulated internally
  2. For lists or other nodes with the same structure, add a unique key attribute to each item to facilitate the reuse of this node in the React diff algorithm and reduce the creation and deletion of nodes
  3. Render: onClick={() => {doSomething()}}; render: onClick={() => {doSomething()}}; render: onClick={() => {doSomething()}}; This will only be created once
  4. If the component props needs to perform a series of operations to get the final result, use the ResELECT library to cache the result. If the props value does not change, the result is directly fetched from the cache to avoid expensive operations
  5. Webpack-bundle-analyzer analyzes the dependencies of the current page to see if there are any unreasonableness, and if so, finds optimization points and optimizes them