1. How do I get the largest number in an array

1. Es6 extension operator…

Math.max(... arr)Copy the code

2. Es5 apply(same principle as Method 1)

Math.max.apply(null,arr)
Copy the code

3. The for loop

let max = arr[0];
for (let i = 0; i < arr.length - 1; i++) {
    max = max < arr[i+1]? arr[i+1] : max
}
Copy the code

4. The array sort ()

arr.sort((num1, num2) = > {
    return num1 - num2 < 0
})
arr[0]
Copy the code

5. Reduce the array

arr.reduce((num1, num2) = > {
    return num1 > num2 ? num1 : num2}
)
Copy the code

2. Usage scenarios of arrays and linked lists

Array application scenario: less data; A common operation is to access data elements by ordinal; Arrays are easier to implement and are supported by any high-level language; The constructed linear table is relatively stable.

Application scenarios of linked lists: It is difficult to estimate the length or size of linear lists; Frequent insertion and deletion operations; Build dynamic linear tables.

3. Understand the sorting algorithm, say the difference between bubble sort and fast sort

Bubble sort is a simple sorting method, its basic idea is: through the comparison and exchange between two adjacent elements, so that the larger elements gradually move from the front to the back (ascending order), like bubbles under the water gradually bubble up, so it is called “bubble” sort.

Quick Sort is an improved method of bubble Sort. In bubble Sort, the comparison and exchange of elements are carried out between adjacent elements, and the exchange of elements can only move one position at a time, so the number of comparison and move is more, and the efficiency is relatively low. In quick sort, elements of comparison and exchange is, at both ends to the middle of the larger elements round can exchange to the back of the position, but smaller elements can exchange next to the front position, elements, the distance of each move further, so is less number and mobile number, speed faster, so it is called the “quick sort”.

4. Backpack problem

5. Browser cache

6. What happens when you type a string of urls into your browser?

1. Enter the URL and press Enter

2. The browser searches for the IP address based on the domain name

3. The browser opens the TCP connection (the default port is 80) and sends an HTTP request to the IP address. If the browser stores cookies under this domain name, the cookies will also be placed in the browser

4. The server sends a permanent redirection response of 306 to the browser.

5. The browser sends an HTTP request based on the redirected address

6. The server analyzes the HTTP request, generates an HTTP response, and sends the response to the client

7. After receiving the response, the browser generates the home page frame and sends a request to the server for the home page resources, such as pictures and videos

8. For static page content, browsers typically cache it. For dynamic pages, browsers typically do not cache. The cache time is also valid

9. The browser sends asynchronous requests to the server because the client needs to keep in touch with the server after some pages are displayed

10. After the whole process is complete, the browser closes the TCP connection

7. Vm. $set theory

8. How does deep copy solve circular references

You only need to determine whether an object’s fields reference the object or any of its parents

function deepCopy2(obj, parent=null) {
    // Create a new object
    let result = {};
    let keys = Object.keys(obj),
         key = null,
         temp = null,
         _parent = parent;
    // If the field has a parent, you need to trace the parent of the field
    while(_parent) {
        // If the field references its parent, it is a circular reference
        if(_parent.originParent === obj) {
            // A circular reference returns a new object of the same class
            return _parent.currentParent;
        }
        _parent = _parent.parent
    }
    for(let i=0,len=keys.length; i<len; i++) { key = keys[i] temp = obj[key]// If the value of the field is also a new object
        if(temp && typeof temp === 'object') {
            result[key] = deepCopy(temp, {
                // Perform deep copy recursively, passing the peer object to be copied and the new object to parent, facilitating the traceability of circular references
                originParent: obj,
                currentParent: result,
                parent: parent
            });
        } else{ result[key] = temp; }}return result;
}
 
const obj1 = {
    x:1
}
obj1.z = obj1;
 
const obj2 = deepCopy2(obj1);
Copy the code

9. React vs. Vue

10. Talk about front-end routing

Routing displays different content or pages based on different URLS

In the early days of routing, the back end directly reload the page according to the URL, that is, the back end controls the routing.

Later, the page became more and more complex, and the server was under more and more pressure. With the advent of Ajax (asynchronous refresh technology), the page realized non-reload to refresh data, so that the front end could control url self-management, and the front end routing was born from this.

Single-page applications are implemented because of front-end routing.

The implementation of front-end routing is actually very simple. In essence, it is to detect url changes, intercept URL addresses, and then parse them to match routing rules.

Before 2014, routing was done with hash, the #. Subsequent hash changes do not cause the browser to make a request to the server, and the browser will not refresh the page if it does not make a request. In addition, every time the hash value changes, the hashchange event is triggered, which tells us what the hash value has changed.

After 2014, because the HTML5 standard was released. Two new apis, pushState and replaceState, allow you to change urls without sending requests. There’s also an onPopState event. This allows you to implement front-end routing in a different way, but in the same way that you implement hash.

1.Pjax (PushState + Ajax)

How it works: The default jump to the A tag is replaced with an Ajax request, and the URL is modified using AN API in HTML5

API: history.pushState and history.replaceState

Both apis operate on browser history without causing a page refresh, with pushState adding a new history and replaceState replacing the current history.

Example:

window.history.pushState(null, null, "name/blue");
//url: https://www.baidu.com/name/blue

window.history.pushState(null, null, "/name/orange");
//url: https://www.baidu.com/name/orange
12345
Copy the code
2.Hjax (Hash + Ajax)

How it works: A # is often used in a URL to represent an anchor (like the back to the top button) and a hash in a route.

The Web service does not parse hash, which means that the Web service automatically ignores everything after #, but JavaScript can be read using window.location.hash, and the path can be read and parsed to respond to the logic of different paths.

The hashchange event (the event that listens for hash changes), when a hashchange is handled with window.location, the page is not rerendered, but is added to the history as a new page. So we can jump to the page and register Ajax in the HashChange event to change the page content.

11. Webpack workflow

12. How did Webpack handle two introductions

13. Several ways of layout

1. Static Layout

2. Liquid Layout

3. Adaptive Layout

4. Responsive Layout

5. Flexible layout (REM/EM layout)

14. The difference between REM VW

15. How does VUE collect dependencies

In Vue, the getter/setter of object.defineProperty is used to realize the responsivity of data. The important point in vue is the dependency collection, which is the bridge between the calculated property and the dependent property. With dependency collection (Dep), when the getter function of the dependent Object A is executed, Everything that depends on it is collected into A’s dependency library, and when the setter of A executes, everything in the dependency library is executed one by one, notifying the dependency object B. These encapsulated dependencies are injected into the STATIC target property of the Dep when B’s getter executes

16. Vue bidirectional binding principle

DefineProperty (defineProperty, defineProperty, defineProperty)

var obj = {}
Object.defineProperty(obj,"username", {get:function(){
		console.log("get init")},set:function(val){
		console.log("set init")
		document.getElementById('uname').value = val
	}
})
Object.defineProperty(obj,"uname", {set:function(val){
		document.getElementById('username').value = val
	}
})
document.getElementById('username').addEventListener("keyup".function(event){
	obj.username = event.target.value
},false)
document.getElementById('uname').addEventListener("keyup".function(event){
	obj.uname = event.target.value
},false)
//Object.defineProperty has two underlying methods: set and get. The bidirectional binding mainly uses set.
DefineProperty (username, uname); // When we assign values to these attributes, the set method will be called implicitly.
// The set method takes an argument, val, which is the value of its property. In the set method, we can assign this val to the value of the input that we want to bind.
// Bind the keyUP event and assign the input to the two properties defined respectively, thus implementing bidirectional binding of VUE.
// Register the keyUP event for the input, and then enter the value of the input into the obj username property. Set the span value to the value of username, and then set the input window value to the value of username. The input will also update the value, thus completing the bidirectional binding
Copy the code

17. How does functional programming understand pure functions

Pure function: a function that satisfies the condition that the input value is certain and the output value is certain

In general, we need to implement functional programming, and the methods we encapsulate should be abstract, independent of external state, and therefore pure functional, so that the abstract methods are reusable and the output depends only on the input parameters. In fact, JS itself has encapsulated higher-order functions, to a certain extent reflects the idea of functional programming, such as array map, filter, reduce and other methods

18. Briefly describe how the browser renders the page

1 When an HTML tag is encountered, the HTML parser is called to parse it into the corresponding token and build a DOM tree

2 Encountering the style/link tag calls the parser to process the CSS tag and build the CSS style tree

3. Call javascript parser to process script tags when script tags are encountered, bind events, modify DOM tree /CSS tree, etc

4. Merge DOM tree and CSS tree into one render tree

5 Render according to the render tree to calculate the geometry information of each node (this process depends on the graphics library)

6 Draw each node on the screen

19. Redraw and rearrange

Redraw: The browser action that is triggered when the appearance of an element is changed. The browser redraws the element based on its new attributes to give it a new appearance.

Rearrangement: When a part of the render tree must be updated and the node size changes, the browser invalidates the affected part of the render tree and reconstructs the render tree.

20. How to reduce redrawing rearrangements

1. Separate read and write operations

var curLeft=div.offsetLeft;

var curTop=div.offsetTop;

div.style.left=curLeft+1+ "px"; div.style.top=curTop+1+ "px";Copy the code

2. Style set changes, you can add a class, style changes in the class

3. You can use absolute to exit the document flow.

4. Use display: None, do not use visibility, and do not change its z-index

5. If you can implement cSS3, implement cSS3.

21. Why the virtual DOM

The Web interface is built from a DOM tree (a tree stands for data structure), and when one part of it changes, it actually changes a DOM node. The virtual DOM is designed to solve browser performance problems. For example, if there are 10 DOM updates in one operation, the virtual DOM will not immediately manipulate the DOM, but save the diff content of the 10 updates to a local JS object, and finally attch the JS object to the DOM tree for subsequent operations to avoid a lot of unnecessary calculation. Therefore, the advantage of using JS object to simulate DOM node is that the update of the page can be reflected in THE JS object (virtual DOM), and the speed of the JS object operation in memory is obviously faster. After the completion of the update, the final JS object is mapped into the real DOM and submitted to the browser to draw.

22. The diff algorithm

What: Is an algorithm that compares the old and new virtual DOM trees, obtains the differences between them, and determines the minimum DOM update operation.

Why: Reduce the overhead of rendering the real DOM and improve performance.

When: When the page is updated, used for re-rendering.

When data changes in Vue, the set method will call dep. notify to notify all the subscribers Watcher, and the subscribers will call Patch to patch the real DOM. React The next time the state or props update, the render() method returns a different tree. When building fiber, mark effectTags as Placement, Update, Deletion, and so on. The DOM is generated according to effectTag rules when the commitWork builds the real DOM.

Who: Vue(patch, patchVnode, and updateChildren). React(reconcileChildFibers, reconcileChildrenArray, updateHostComponent, and others). How: Depth-first, same-layer comparison. The spanning tree structure varies with the tag. Use keys to identify stable nodes.

23. This section describes the new features of ES6

1. The const and let

2. Template string

3. Some new string methods such as includes, startsWith, endsWith, repeat, padEnd, padStart

4. Functions can specify default arguments

5. Functions can use variable number of arguments

Arrow function

7. Deconstruction

8. Array new methods, such as array.of, array.from (), [].fill(), [].keys(), [].values(), [].entries(), find, findIndex, includes

Class 9.

24. Principles and application scenarios of Vue.nextTick

NextTick has a function called nextTickHandler that iterates through the internal array. This function is executed asynchronously, depending on what type of asynchronous task it is: Micro task or macro task.

After the execution of the main thread, it will fetch tasks from the task queue and execute them in the main thread. The task queue contains micro tasks and macro tasks. The micro task will be fetched first, and the macro task will be executed after the execution of the micro task, and so on. Setting nextTickHandler to a microtask or macro ensures that it is always executed after data modification or DOM update. (See promise timing issues & JS execution mechanism)

Usage scenarios: when data is changed and the view is not rendered as expected; You should consider whether the code was executed in the DOM before it was executed. If so, you should consider putting logic into nextTick. Sometimes business operations are complicated, and some operations may need to be executed later, but they still don’t work as expected in nextTick. Consider using setTimeout to put logic into macro tasks.

25. Why is data a function in Vue components

The data in the component is written as a function, and the data is defined as the return value of the function. In this way, each time the component is reused, a new data is returned, similar to creating a private data space for each component instance and letting each component instance maintain its own data. However, simply writing in object form makes all component instances share a copy of data, which will cause a result that all changes will change.

26. Talk about the cycle of events

Handwriting function tremble and function throttling

Function throttling: after firing a function repeatedly, the first time is executed, and the second time is executed only after the specified execution period

Function stabilization: trigger a function repeatedly, and only make the last function take effect within a specified period of time

/* Throttling function: fn: function to be throttled, delay: specified time */
function throttle(fn,delay){
   // Record the last time the function started
   var lastTime = 0
   return function(){
   		// Record the time when the current function fires
   		var nowTime = new Date().getTime()
   		If the current time minus the last execution time is greater than the specified interval, let it trigger this function
        if(nowTime - lastTime > delay){
             // bind this to
             fn.call(this)
             // Synchronize time
             lastTime = nowTime
         }
   }
}
/* Buffering function: fn: function to be buffered, delay: specified time */
function debounce(fn,delay){
    var timer = null
    // Clear the last delay
    return function(){
         clearTimeout(timer)
         // Reset a new delay timer
         timer = setTimeout(() = > {
                fn.call(this) }, delay); }}Copy the code

28. There are several ways to recycle an array

1. Double cycle comparison of weight loss

2. Create a new array and use indexof to check the new array

3. Reuse through JS object features

4. Es6 set method

29. How many ways to judge variables and what are the differences

1.typeof

String, number, Boolean, symbol, bigint (es10 bigint), undefined, etc.

2.instanceof

Are commonly used to determine the reference data types, such as the Object, Function, Array, the Date, the RegExp, etc., mainly to judge whether an instance belongs to a type

3. The Object. The prototype. The toString () the way this is the most accurate judgment type

Object. The prototype. ToString. Call to get the type, the toString is a method on the Object prototype Object, this method returns to its caller by default specific types, more strictly speaking, Is the type of object pointed to by the toString runtime. The type returned is in the format [object, XXX]. XXX is the specific data type, which includes: String, Number, Boolean, Undefined, Null, the Function, the Date, the Array, the RegExp, Error, HTMLDocument,… Basically all object types can be retrieved using this method.

4.constructor

When a function F is defined, the JS engine adds a Prototype to F, then adds a constructor property to prototype and points it to a reference to F.

Null and undefined are invalid objects and therefore have no constructor. These two types of data can be identified using the fourth method.

JS objects’ constructor is unstable. This is mostly true of custom objects. When developers rewrite Prototype, the original constructor is lost and default to Object

30. Call bind apply new implementation principle

Call the function

The call() method calls a function with a specified this value and one or more arguments given separately. The syntax and actions of this method are similar to those of apply(), except that call() accepts a list of arguments, whereas apply() accepts an array of arguments.

// thisArg, arg1, arg2...
Function.prototype.call = function (context,... args) {
 let context = context ? context : window;
 let args = args ? args : [];
 let key = Symbol(a); context[key] =this;
 letres = context[key](... args);delete context[key];
 return res;
}
Copy the code
The apply function

The apply() method calls a function with a given this value and the arguments supplied as an array (or array-like object).

// func.apply(thisArg, [argsArray])
Function.prototype.apply = function (context,args) {
 let context = context ? context : window;
 let args = args ? args : [];
 let key = Symbol(a); context[key] =this;
 letres = context[key](... args);delete context[key];
 return res;
}
Copy the code
The bind function

The bind() method creates a new function, and when bind() is called, this of the new function is specified as the first argument to bind(), and the remaining arguments will be used as arguments to the new function.

Bind (thisArg[, arg1[, arg2[,...]]])
Function.prototype.bind = function (context,... args) {
  if(typeof this! = ='function') {return new TypeError('must be function');
  }
  let _this=this;
  return function F(. newArgs){
  	if(this instanceof F){
		return new_this(... args,... newArgs); }return_this.apply(context,... args,... newArgs); }}Copy the code
The new function

The new operator creates an instance of a user-defined object type or of a built-in object with a constructor. The new keyword does the following:

  1. Create an empty simple JavaScript object (that is {});

  2. Link this object (that is, set its constructor) to another object;

  3. Use the new object created in Step 1 as the context for this;

  4. If the function does not return an object, this is returned.

    function create(fn,... args){//fn is the function to be new, and args is the argument to the function
      // Create an empty object obj, then link fn's prototype to obj's prototype
      let obj = Object.create(fn.prototype);
      // Bind this to implement inheritance, obj can access the properties in the constructor
      let res = fn.apply(obj,args);
      Object /array/function takes precedence over obj if it is of any other type
      return res instanceof Object ? res : obj;
    }
    Copy the code