React and common front-end interview questions (reading this one is enough) are being continuously updated...

Table of contents

1. Tell me about your understanding of React? What are the characteristics?

2. Tell me how the Real diff algorithm works?

3. Tell me about the different stages of the React life cycle? What is the method corresponding to each stage?

4. Tell me about your understanding of virtual dom in React?

5. Tell me about your understanding of react hook?

6. How to communicate between React components?

7. Tell me about your understanding of controlled components and uncontrolled components? Application scenario?

8. Tell me about the principle of the Connect component?

9. Talk about the essence of jsx syntactic sugar in react?

10. Tell me about your understanding of redux middleware? What are the commonly used middleware? Implementation principle?

11. Tell me about the difference between AMD, CMD, and commonJS modular specifications?

12. Tell me about the version number rules in package.json?

13. Tell me about the process of converting React jsx into real DOM?

14. Tell me about your understanding of @reduxjs/toolkit? What is the difference with react-redux?

15. The principle of the React render method, when will it be triggered?

16. What are the means of React performance optimization?

17. How to implement a throttling function and anti-shake function through native js?

18. Tell me about your understanding of the onion model in koa?

19. Talk about how to optimize front-end performance with webpack?

20. Tell me about your understanding of webSocket?

21. What is the difference between bind, call, and apply? How to implement a bind?

22. What are anti-shake and throttling? What's the difference? How to achieve?

23. How to understand reflow and redraw? Under what circumstances will it be triggered?

24. What is the principle of VUE routing?

25. Do you know the diff algorithm of vue? Tell me?

26. Tell me about your understanding of keep-alive?

27. What is responsive design? What are the basic principles of responsive design? How to do?

28. How to solve the cross-domain problem?

29. How to optimize webpack packaging speed?

30. How to solve the slow loading speed of the first screen of SPA?

31. How many modes does react router have? Implementation principle?

32. What are the steps from inputting url in the address bar of the browser to displaying the page?

33. Tell me about the data types in JavaScript? Storage difference?

34. Tell me about your understanding of React Hooks? What problem did it solve?

35、说说你对promise的了解?

36、 说说webpack中常见的Loader?解决了什么问题?

37、说说 React 性能优化的手段有哪些?

38、 说说 React中的setState执行机制?

39、 Vue组件之间的通信方式都有哪些?

40、 说说React生命周期中有哪些坑?如何避免?

41、调和阶段setState干了什么?

42、说说redux的实现原理是什么,写出核心代码?

43、 React合成事件的原理?

44、 为什么react元素有一个$$type属性?

45、说说你对redux中间件的理解?常用的中间件有哪些?实现原理?

46、说说你对事件循环event loop的理解?

47、前端跨域的解决方案?

48、数组常用方法及作用,至少15个?

49、说说你对vue中mixin的理解?

50、for...in循环和for...of循环的区别?

51、Js数据类型判断都有哪几种方式?至少说出5种?它们的区别是什么?

52、说说你对Object.defineProperty()的理解?

53、Vue中自定义指令的理解,应用场景有哪些?

54、说说javascript内存泄漏的几种情况?

55、大文件如何做断点续传?

56、原生js如何实现上拉加载下拉刷新?

57、说说设备像素、css像素、设备独立像素、dpr、ppi之间的区别?

58、谈谈你对BFC的理解?

59、说说TCP为什么需要三次握手和四次握手?

60、前端性能优化的手段有哪些?

61、最少说出三种前端清除浮动的方法?

62、什么是强缓存和协商缓存?

63、说说你对栈、队列的理解?应用场景?

64、说说你对git rebase 和git merge的理解?区别?

65、说说git常用的命令有哪些?

66、Vue组件通信?

67、说说你对vuex的理解?写出其原理的核心代码?

68、props和state相同点和不同点?render方法在哪些情况下会执行?

69、react新出来两个钩子函数是什么?和删掉的will系列有什么区别?

70、CDN的特点及意义?

71. What is a closure and what is the application scenario?

72. Tell me about your understanding of the browser kernel?

73. How many ways to clear the float? Pros and cons of each?

74. If you need to write animation manually, how long do you think the minimum time interval is, and why?

75. Tell me about the difference between Real DOM and Virtual DOM? Advantages and disadvantages?

76. Tell me about the event mechanism of react?

77. Tell me about your understanding of fiber architecture? What problem did it solve?

78. What is the principle of react diff?

79. How to use css to realize a triangle?

80. What is the function of shouldComponentUpdate?

81. Tell me about your understanding of git rebase and git merge? the difference?

82. In the process of using redux, how to prevent the constant duplication of the defined action-type?

83. Talk about the virtual dom in React? What is the relationship between diff and key during virtual dom calculation?

84. React's props.children uses the map function to traverse and will receive an exception display. Why? How should it be traversed?

85. Tell me about your understanding of immutable.js?

86. Redux is originally synchronous, why can it execute asynchronous code? What is the realization principle? What is the implementation principle of middleware?

87. What is the biggest difference between synchronous action and asynchronous action in redux?

88. What are the differences and usage scenarios between redux-saga and redux-thunk?

89. Why is the ordinary for loop more efficient than the forEach loop?

90. What is the 1-pixel solution for the mobile terminal?

91. What is the scaling mechanism in flexbox?

92. Tell me about your understanding of mixin in vue?

93. What is the difference between for...in loop and for...of loop?

94. What is the publish-subscribe model, and write its core implementation code?

95. Tell me about your understanding of the viewport?

96. Tell me about your understanding of useEffect, which life cycles can be simulated?

97. Talk about the difference between setState and replaceState in React?

98. Talk about the working principle of onClick binding in react?

99. What is vertical margin consolidation? Tell me about the situation after the merger?

100. How to deal with the dependency of useEffect as a reference type?

101. Do you know the createPortal in react, and talk about its usage scenarios?

1. Portal, which renders child nodes to DOM nodes that exist outside the parent component. 2. ReactDOM.createPortal(child, container) The first parameter (child) is any renderable React child element, such as an element, string or fragment. The second parameter (container) is a DOM element. 2. Portals are suitable for components that are out of flow, especially for components with position: absolute and position: fixed. Such as modal box, notification, warning, goTop, etc.

version 2.0

1. Tell me about your understanding of Event Loop?

2. Tell me about your understanding of BOM. What do you know about common BOM objects?

3. What are the kernels of browsers, and what are the differences?

4. Tell me about the difference between progressive enhancement and graceful degradation of browsers?

5. What are the solutions for website performance optimization?

6. What is the difference between Link and @import?

7. Tell me about your understanding of BFC. What are the triggering conditions?

8. What is the difference between null and undefined?

9. What are the ways in which elements in css are separated from the document flow? What are the positioning methods and the differences?

10. What is the difference between synchronous and asynchronous?

11. What is the difference between pseudo-classes and pseudo-elements? What are the new selectors in Css3?

12. Tell me about the difference between Promise and async/await?

13. Talk about the difference between rearrangement and redrawing? What are the trigger conditions?

14. How does Javascript implement inheritance?

15. What is strict mode and what are the restrictions?

16. How to quickly disturb the order of an array, such as var arr = [1,2,3,4,5,6,7,8,9,10]?

17. What are the custom command hook functions of Vue? What have you done with custom directives?

18. Jump from page A to page B, cache component A, jump from component A to component C, cancel cache, how to achieve?

19. What are the responsive principles and differences between Vue2 and Vue3?

20. How does Vue implement permission management, and how to realize button-level permissions?

21. The difference between Vue2 and Vue3 is at least 5 points?

22. The process of component communication in Vue3 [father to son, son to father]?

23. What is the principle of Apply/call/bind?

24. Tell me about your understanding of prototype and prototype chain?

25. Tell me about your understanding of Generator in ES6?

26. Tell me about the difference between the browser event loop and the nodeJs event loop?

27. Tell me about your understanding of browser caching mechanism?

28. Tell me about your understanding of the browser kernel?

29. Tell me about your understanding of Vue's responsive principle?

30. What is the difference between Methods watch computed?

31. Tell me about your understanding of Virtual DOM?

32. Tell me about your understanding and function of nextTick?

33. Tell me about your understanding of webpack?

34. Talk about the difference between GET and POST?

35. Talk about the difference between HTTP and HTTPS. What is the encryption principle of HTTPS?

36. Why does TCP need three handshakes?

37. Tell me about the principle of Proxy proxy?

38. Talk about the understanding of memory leaks? What are the situations of memory leaks?

39. Tell me about the difference between arrow functions and ordinary functions?

40. How to solve the slow loading speed of the first screen of SPA?

41. Talk about the common Loader in webpack? What problem did it solve?

42. What is your understanding of SPA single page, what are its advantages and disadvantages? How to realize SPA application?

43. What is the difference between components and plugins in Vue?

44. What are the communication methods between Vue components?

45. Do you know the diff algorithm of vue? Tell me?

46. ​​Briefly talk about Virtual Dom?

47. What is the difference between the Composition Api used by Vue3.0 and the Options Api used by Vue2.x?

48. Talk about the setState execution mechanism in React?

49. Talk about the understanding of class components and function components in React? What's the difference?

50. Tell me about your understanding of React Hooks? What problem did it solve?

51. How do UseMemo and useCallback improve performance, and what are the application scenarios?

52. What is the implementation principle of Vue-router?

53. How to package components and use them between different projects?

54. What is the difference between vue, react, and angular?

55. Tell me about your understanding of Redux? How it works?

56. Tell me about your understanding of the box model?

57. What are the selectors of CSS? Priority? Which can be inherited?

58. What are the methods of centering elements horizontally and vertically? What if the element has a variable width and height?

59. How to understand reflow and redraw? Under what circumstances will it be triggered?

60. What is responsive design? What are the basic principles of responsive design? How to do?

61. Tell me about your understanding of the box model?

62. How to center a box horizontally and vertically? What are the methods?

63. Tell me about the data types in JavaScript and how to store them?

64. How to understand responsiveness? What are the ways to achieve it? What's the difference?

65. What are the common methods of Css performance optimization, and how to achieve them?

66. What are the methods to judge the data type? What's the difference?

67. What is the difference between Bind, Call and Apply? How to implement a bind method?

68. How to understand closure? What is the application scenario of closure?

69. Briefly talk about what is an event agent?

70. What are anti-shake and throttling? What's the difference? How to achieve?

71. Tell me about your understanding of the scope chain?

72. Talk about the understanding of prototype and prototype chain?

73. What are the life cycle and meaning of vue?

74. What are the hook functions of vue custom instructions?

75. What are the JavaScript local storage? Differences and usage scenarios?

76. Tell me about your understanding of recursion? Encapsulate a method to achieve tree structure encapsulation with recursion?

77. What is the difference between Link and @import?

78. What is FOUC? How to avoid it?

79. Tell me about your understanding of precompilers?

80. What is the function of shouldcomponentUpdate?

81. Outline transaction processing logic in React?

82. What is the division of React components into business components and technical components?

83. Which periodic function is React performance optimization?

84. Talk about the understanding and application scenarios of the Fiber architecture?

85. React performance optimization solution?

86. Briefly describe the process of flux and css rendering?

87. What is the difference between DOM0, DOM2, and DOM3 event processing?

88. How to judge that the page scrolls to the bottom, and how to judge whether the elements in the page enter the visualization area?

89. Tell me about the difference between the browser Event Loop and the Event Loop in nodejs?

90. Tell me about the underlying implementation principle of vue-router?

91. Tell me about the realization principle of vuex? How are the commit and dispatch methods implemented?

92. There are three components A, B, and C. A component jumps to B component cache, and A component jumps to C component without caching. How to achieve it?

93. Understanding of MVVM?

94. Please explain in detail your understanding of the vue life cycle?

95. What are the data transfer methods between vue components?

96. Routing implementation of vue: principles of hash mode and history mode?

97. What are the hook functions of vue routing?

98. What is the difference between v-if and v-show?

99. What is the difference between $route and $router?

100. How to make CSS only work in the current component?

101. What is the function of the function?

102. Steps to use plugins in vue?

103. Please list three common life cycle hook functions in vue?

104. What is Vue SSR?

105. What are the advantages of Proxy over definedProperty?

106. What is vuex? how to use? Which functional scenarios use it?

107. Vue2.x responsive principle?

108 What is the difference between ES5, ES6 and ES2015?

109. What is the function of let? Why use let with var?

110. Give some common upgrades and optimizations for String strings in ES6?

111. Give some common upgrades and optimizations for the Array array type in ES6?

version 1.0

1. Tell me about your understanding of React? What are the characteristics?

1. React is a JavaScript library for building user interfaces. It only provides solutions at the UI level. It follows component design patterns, declarative programming paradigms, and functional programming concepts to make front-end applications more efficient. 
2. Use virtual DOM to effectively operate DOM, follow the one-way data flow from high-level components to low-level components, and help us divide the interface into independent small blocks, each block is a component, and these components can be combined , nested, constitute the overall page. 
3. Features: JSX syntax, single item data binding, virtual DOM, declarative programming, Component

2. Tell me how the Real diff algorithm works?

1. The diff algorithm is designed to save performance. Compared with the same level, the performance is more efficient without crossing levels. 2. The 
operation process is mainly divided into three layers: tree layer, component layer, element layer 
    1, tree layer: tree layer The operation of cross-level movement of DOM nodes is ignored, and only the DOM nodes of the same level are compared. Once the node is found not to exist, the node and all the following child nodes are directly deleted 
    . tree diff, for hierarchical comparison, when encountering different types of components, directly judge this different component as a dirty component, and replace all child nodes under this component, when you know that the virtual DOM of this component has not changed, you can Manual use, shouldComponentUpdate is used to determine whether diff is required, which further improves the efficiency and performance of diff. 
    3. element layer: below the same level, it can perform insert operations for new nodes; for redundant nodes, perform delete operations; For the transposed node, perform the operation of moving

3. Tell me about the different stages of the React life cycle? What is the method corresponding to each stage?

1. React life cycle is mainly divided into three stages: creation stage, update stage and uninstallation stage 
2. Creation stage: 
    1. constructor: used to define the state, or to store some this methods; 
    2. getDerivedStateFromProps(): Will be used in the future, need to return a new object as a new state or return null to indicate that the state state does not need to be 
    updated 
    4. componentDidMount(): used to perform some data acquisition, event monitoring and other operations 
3. Update phase: 
    1. getDerivedStateFromProps(): will be used in the future, and needs to return a new object as the new state or return null to indicate that the state state is not valid Need to update 
    2. shouldComponentUpdate: used to tell the component itself whether to re-render the component based on the current props and state, and return true by default 3. 
    render: a method that must be implemented by the class component, used to render the DOM structure, and can access the component state and prop Attribute 
    4, getSnapshotBeforeUpdate: This periodic function is executed after render, and the DOM element has not been updated at the time of execution. The purpose is to obtain some information before the component is updated, such as the scroll position of the component. After the component is updated, it can be based on this information Restore some UI visual states 
    5. componentDidUpdate: You can perform corresponding operations according to the changes of props and state before and after, such as obtaining data, modifying DOM styles, etc. 
4. Unloading stage:
    componentWillUnmount: This method is used to clean up some registrations to listen to events, or unsubscribe network requests, etc., before the component is unmounted. Once a component instance is unmounted, it will not be mounted again, but can only be recreated

4. Tell me about your understanding of virtual dom in React?

1. The virtual DOM uses the form of js objects to simulate the nesting relationship of the page dom; 
2. The virtual DOM is a virtual JavaScript object tree. The key point is that "virtual" and "JS object" refer to the Real web page document nodes are virtualized into js objects one by one, and stored in memory in a tree structure. 
3. Realization principle: Simulate web page document nodes through JS, generate JS object tree (virtual DOM), and then further generate real DOM tree, and then draw to the screen. If any content changes later, React will regenerate a brand new virtual DOM tree, then compare and diff with the previous virtual DOM tree, package the difference into a patch, apply it to the real DOM, and then render it to the screen for browsing device.

5. Tell me about your understanding of react hook?

1. Hook is a new feature/grammar added in React 16.8.0, which allows you to use state and other React features in function components. 
Common Hooks: 
2. useState: Similar to state in class components, it is convenient for us to define initialization The data, receive two parameters, one is to initialize the data, the other is to modify the data method 
3, useEffect: side effect function, only after use, will produce side effects, it accepts two parameters, one is a function, the other is to The monitored data can be [], which means that it is only executed once, and parameters can also be passed. After the parameters are passed, it will only be triggered when our data changes. If not written, it will be executed once when a change occurs. 4. useMemo 
: Data cache, when we communicate between components, if the data in our parent component changes, our subcomponents will also be updated accordingly, regardless of whether the updated data is related to the data of our subcomponents, he will Perform an update operation. At this time, there will be a waste of update performance. We can use ysememo to cache and reduce unnecessary update operations. The parameter of his cache is a string. If it is a function, then our usememo It will be invalid. At this time, you need to use useCallback to cache the data. 
5. useRef: You can monitor the change of our input box data and get the value in the input box

6. How to communicate between React components?

React component communication means that the value component transmits information in a certain way to achieve a certain purpose. 
    Way: 
    1. The parent component transmits information to the child component: Since the data flow of react is one-way, when the parent component calls the child component, it only needs to be in Parameters are passed in the sub-component tag, and the sub-component receives through the props attribute 
    2. The sub-component transmits information to the parent component; the parent component passes a function to the sub-component, and then through the callback of this function, the value passed by the sub-component is obtained 3. 
    Brothers Transfer between components: the parent component acts as an intermediate layer to achieve data intercommunication, by using the parent component to transfer 
    4, the parent component transfers values ​​to the descendant components: using a way of component communication provided by context, data sharing can be realized, Provider The component passes the value attribute to the descendant component 
    5. Non-relational components pass data: manage the data as a global resource, so as to realize the communication function between components, such as 
redux

7. Tell me about your understanding of controlled components and uncontrolled components? Application scenario?

1. Controlled components: In React, mutable state is usually stored in the component's state property and can only be updated using setState(), while the React component that renders the form also controls what happens in that form on subsequent user input Circumstances, in which input form elements controlled by React change their values, are called controlled components. Simply put, it receives the control of setState, and the state of the component responds to external data throughout the process. 
2. Uncontrolled components: form data is processed by the DOM itself. That is, it is not controlled by setState(), similar to traditional HTML form input, the input input value displays the latest value (use ref to obtain the form value from DOM), and is not controlled by setState. Generally, it receives external data during initialization. Then store its own state internally 
Application scenarios: 
    1. Controlled components: Mandatory input format, multiple inputs of one data, dynamic input, verification problems when submitting 
    2. Uncontrolled components: One-time value (submit ), validation on submission

8. Tell me about the principle of the Connect component?

1. Connect connects redux and react, wraps it in the outer layer of our container component, receives the state and dispatch in the store provided by the Provider above, passes it to a constructor, returns an object, and passes it to our container component in the form of attributes 2 
. Connect is a high-level function, first pass in mapStateToProps, mapDispatchToProps, then return the Component function, and then pass in the real Component as a parameter to return a new component

9. Talk about the essence of jsx syntactic sugar in react?

1. The essence of Jsx is the grammatical sugar of the function React.createElement. All jsx syntax will eventually be converted into React.createElement through babel.js. 
2. Three parameters: type refers to the current element type, config is jsx Attributes are stored in the form of object attributes and values, and children are the content stored in the tag 
3. JSX writing method: Babel must be introduced and the type of the script tag must be set to text/bable Babel: convert jsx to React.createElement() function call

10. Tell me about your understanding of redux middleware? What are the commonly used middleware? Implementation principle?

1. Redux middleware is a type of software between the application system and system software. It uses the basic services provided by the system software to connect various parts of the application system or different applications on the network to achieve resource sharing and function sharing. 
2. Commonly used middleware: redux-thunk is used for asynchronous operations, and redux-logger is used for log records 
Implementation
principle: All middleware are nested and executed in an array, the data type passed is judged, and finally store is executed .dispatch, the middleware API inside the middleware can get the getstate and dispatch methods.

11. Tell me about the difference between AMD, CMD, and commonJS modular specifications?

1. AMD: This specification is an asynchronous loading module. First define all dependencies, and then execute require(['xxx'], function(){}) in the callback function after the loading is completed. 2. CMD: The principle of dependency proximity, 
use When writing function(require,exports,module){require('xxx')} 
3. commonJS: use require('xxx') to load modules. 
The difference: 
    1. The biggest difference between AMD and CMD is the execution timing of dependent modules The processing is different, both are asynchronous loading modules 
    2, AMD depends on the front, js can easily know who the dependent module is, load it immediately, CMD depends on the nearest, need to change the module into a string analysis 
    3, commonJS is all codes run In the module scope, it will not pollute the global scope. The module loading is synchronous. Only after the loading is completed, the following operations can be performed. The value of requeire is a copy of the output value, and the change of the module content will not affect this value.

12. Tell me about the version number rules in package.json?

^: will only perform updates that do not change the non-zero number to the left 
~: if ~0.13.0 is written, then when npm update is run, it will update to the patch version 
>: receive any version higher than the specified version 
>= : accept any version equal to or higher than the specified version 
<=: accept any version equal to or lower than the specified version 
<: accept any version lower than the specified version 
=: receive the exact version 
-: accept a range of versions 
||: Combined collection 
Unsigned: Receive the specific version specified 
Latest: Use the highest version available

13. Tell me about the process of converting React jsx into real DOM?

1. Use React.createElement or jsx to write react components. In fact, all jsx codes will be converted into React.ccreateElement(...), and babel will help us complete the conversion process. 2. The createElement 
function is for special props such as key and ref Process, and get defaultProps to assign default props, and process the incoming child nodes, and finally form a virtual DOM object 3. 
ReactDOM.render renders the generated virtual DOM to the specified container, which uses Batch processing, transaction and other mechanisms are optimized for specific browsers, and finally converted to real DOM

14. Tell me about your understanding of @reduxjs/toolkit? What is the difference with react-redux?

1. React-redux is the official react UI binding layer that allows React components to read data from the redux store and dispatch operations to the store to update the state. APIs such as connect and Provider are provided to help us connect react and redux, and the implemented logic will be more rigorous and efficient. 
2. @reduxjs/tookit is a secondary package of Redux. The difference between creating store and updating store 
    : 
    1. Reduxjs/tookit is more convenient than react-redux. It integrates redux-devtools-extension and does not require additional configuration. It is very convenient. 2. 
    Reduxjs/tookit integrates the function of immutable-js, No need to install, configure and use, which improves development efficiency 
    3. reduxjs/tookit integrates the functions of redux-thunk 
    4. reduxjs/tookit puts types, actions, and reducers together to form new slices, which simplifies our use

15. The principle of the React render method, when will it be triggered?

The Render function has two forms in react. In the class component, it refers to the render method. In the function component, it refers to the function component itself. In render, we will write jsx, and jsx will be converted into familiar js format, during the render process, React compares the tree returned by the newly called render function with the tree of the old version, decides how to update the DOM, and then performs a diff comparison to update the DOM tree Trigger timing: 1. Class components call setState 
    to 
        modify state; 
        2. When the function component modifies the state through useState Hook; 
        3. When the class component is re-rendered; 
        4. When the function component is re-rendered 
;

16. What are the means of React performance optimization?

1. Through shouldComponentUpdate: compare state and props to determine whether to re-render, return true by default, and do not want rendering to return false 2. PureComponent: realize 
by comparing the comparison results between state and props 
3. React.memo: Cache the rendering of components to avoid Unnecessary updates (only for function components) 
4. Avoid using inline functions: every time render is called, a new function will be re-rendered, a function will be created inside the component, and the event will be bound to the function itself 
5 . Use React Fragments to avoid additional markup 
6. Use Immutable: reduce the number of renderings 
7. Lazy loading components: use suspense and lazy components to achieve code splitting function 
8. Event binding method 
9. Server-side rendering

17. How to implement a throttling function and anti-shake function through native js?

1. Function throttling: Trigger frequently, but only execute the code once within a specific time 
2. Function anti-shake: Trigger frequently, but only execute the code once when the execution condition is not triggered within a specific time 
3. Difference: Both The difference is that function throttling is to do a certain thing at a fixed time, such as sending a request every 1 second. The anti-shake function is executed only once after being triggered frequently (the premise of both is frequent triggering) 
. Want to get the position of the scroll bar, and then perform the next action 
5. Anti-shake application scenarios: input box search auto-completion events, frequent operations like and cancel likes, etc. These application scenarios can also be realized through function throttling , frequently operate likes and cancel likes, so it is necessary to obtain the last operation result and send it to the server

18. Tell me about your understanding of the onion model in koa?

1. In koa, the middleware is divided into two parts by the next() method. The upper part of the next method will be executed first, and the lower part will be executed after all subsequent middleware executions are completed. 2. In the onion model, each layer is equivalent 
to A middleware, used to handle specific functions, such as error handling, session processing, etc., the processing order is first the next() request, then execute the next() function, and finally the next() response, that is to say, each middleware There are two processing opportunities. 
3. The core principle of the onion model is to use the componse method

19. Talk about how to optimize front-end performance with webpack?

1. Compress code: delete redundant code, comments, simplify code writing, etc. You can use webpack's UglifyJsPlugin and ParallelUglifyPlugin to compress JS files 
2, use cssnano (css-loader?minimize) to compress css 
3, use CDN to accelerate: During the construction process, modify the referenced static resource path to CDN on the corresponding path. You can use webpack for the output parameter and the publicPath parameter of each loader to modify the resource path 
4. Tree Shaking: Delete the fragments in the code that will never be accessed. 
It can be achieved by adding the parameter --optimize-minimize when starting webpack 
5. Code Splitting: Divide the code into chunks according to the route dimension or component, so that it can be loaded on demand and can make full use of the browser cache 
6. Extract public third-party libraries: SplitChunksPlugin plug-in for public module extraction, 
7. Use browser cache to cache these public codes that do not require frequent changes for a long time

20. Tell me about your understanding of webSocket?

1. Understanding: webSocket is a network transmission protocol, located in the application layer of the OSI model, which can perform duplex communication on a single TCP connection, which can better save server resources and bandwidth and achieve real-time communication. The client and the server only need to complete a handshake, and a persistent connection can be created between the two, and two-way data transmission can be performed. 2. 
Features: 
    1. Full-duplex (communication allows data to be transmitted in two directions simultaneously) 
    2 . Binary frame (using the binary frame structure, the syntax and semantics are completely incompatible with HTTP, and more focused on real-time communication) 3. 
    Protocol name (ws and wss are introduced to represent the websoket protocol of plaintext and ciphertext respectively, and the default port is 80 or 443 , almost exactly the same as http) 
    4. Handshake (there is a handshake process and then formally send and receive data)

21. What is the difference between bind, call, and apply? How to implement a bind?

Call, bind, and apply all change the this point when the function is executed. Differences 
    : 
    1. apply receives two parameters, the first parameter is the this point, and the second parameter is the parameter received by the function, which is passed in as an array 
    2 . The first parameter of the Call method is also pointed to by this, and a parameter list is passed in later. 
    3. The Bind method is similar to call. The first parameter is also pointed to by this, and a list of parameters is passed in later (this list can be divided into multiple second pass), bind is to return the function 
after binding this , apply and call are executed 
immediately { 
    Determine whether the calling object is a function 
    If(typeof this !== 'function'){throw new TypeError("error")} 
    Get parameters 
    Const args = [...arguments].slice(1) 
    Fn = this 
    Return function Fn (){ 
According to the calling method, pass in different binding values 
    ​​Return fn.apply(this instanceof Fn ? new fn(...arguments):context,args.concat(...arguments)) 
} 
}

22. What are anti-shake and throttling? What's the difference? How to achieve?

Throttling: Only one time is allowed within n seconds. If it is triggered repeatedly within n seconds, only one time will take effect. 
Anti-shake: The event will be executed after n seconds. If it is repeatedly triggered within n seconds, the timing will be re-timed. Differences 
: 
    1. Function anti- After a period of continuous operation, the callback is processed by using clearTimeout and setTimeout; function throttling, in a period of continuous operation, each event is only executed once, and it is used in high-frequency events to improve performance 2. Function anti- 
    shake Pay attention to the time of continuous triggering for a certain period of time, and only execute it once at the end, while the function throttling is only executed once in a period of time

23. How to understand reflow and redraw? Under what circumstances will it be triggered?

Reflow: The layout engine will calculate the position and size of each box on the page according to various styles 
Redraw: After calculating the position, size and other properties of the box model, the browser will redraw the trigger 
timing according to the characteristics of each box : 
    Reflow: Add or delete visible DOM elements; the position of elements changes, the size of elements changes, and the content changes, such as text changes or pictures are replaced; when the page starts to render, the browser window size changes and redraws 
    : Redrawing must be triggered when reflow is triggered. In addition, there are color changes, text direction changes, shadow changes, etc.

24. What is the principle of VUE routing?

Routing is divided into two modes: hash mode and history mode. 
Principle: 
    Hash: The hash value in url is a state of the client. When sending a request to the server, the hash part will not be sent, and the change of the hash will be displayed in the browser. Add a record to the access history of the browser, so we can control the switching of the hash through the back and forward buttons of the browser, and jump the page by changing the hash value. History: In history mode, the front-end 
    URL must be the same as the actual The url that initiates the request to the backend is consistent, and the pushState and replaceState two APIs are used to operate and realize the change of the url. You can operate the history of the browser without refreshing the page, or use popstate to monitor the change of the url, so as to realize Page jump function

25. Do you know the diff algorithm of vue? Tell me?

The Diff algorithm is an efficient algorithm for comparing tree nodes on the same level. It has two characteristics: comparisons are only made in the same level, and changes are compared across levels; in the process of diff comparison, the loop moves from both sides to the middle Principle of comparison 
: 
    1. When the data changes, the set method will call Dep.notify to notify all subscriber watchers, and the subscribers will call patch to patch the real DOM and update the corresponding view. 2. Every 
    diff will call updateChildren method to compare, and then recursively go down layer by layer until all child nodes in the old Vnode and new Vnode are compared. The process of domDiff is more like the comparison of two trees. Every time the same node is found, their child nodes will be compared layer by layer. It is a process of deep recursive traversal comparison.

26. Tell me about your understanding of keep-alive?

1. Keep-alive is a built-in component in vue. It can keep the state in memory during component switching to prevent repeated rendering of DOM, which is the so-called component cache. 2. When Keep-alive wraps dynamic 
components, it will not be cached Active component instances instead of destroying them 
3. Keep-alive can set the props attribute: include string or regular expression, which will be cached only when the name matches; 
4. exclude: string or regular expression, any name Matched components will not be cached, max number, how many component instances can be cached at most

27. What is responsive design? What are the basic principles of responsive design? How to do?

    Responsive website design: It is a kind of network page design layout. The design and development of the page should respond and adjust correspondingly according to user behavior and equipment environment (system platform, screen size, screen orientation, etc.) The basic principle of responsive design: 
    yes Detect different device screen sizes through media queries for processing. In order to handle mobile terminals, the page header must have a meta statement viewport 
Implementation method: 
    1. Media query: set different types of media conditions, and give corresponding conditions according to the corresponding conditions The style sheet corresponding to the media call 
    2. Percentage: When the width or height of the browser changes, the width and height of the components in the browser can be changed with the change of the browser through the percentage unit, so as to achieve responsiveness The effect of the formula 
    3. vw/vh: vw represents the width relative to the view window, and vh represents the height relative to the view window. For elements at any level, in the case of vw units, 1vw is equal to one percent of the view width 
    4. rem: rem is the font-size attribute relative to the root element html. By default, the font size of the browser is 16px. when 1rem = 16px

28. How to solve the cross-domain problem?

Due to the cross-domain problem caused by the same-origin policy restriction of the browser, when the browser requests the resources of another domain name from the web page of one domain name, any difference in domain name, port, or protocol is cross-domain. Solution: 1. jsonp cross 
- 
    domain Domain 
    2, Nginx reverse proxy 
    3, Php end modify header 
    4, Document.domain realizes mutual access and operation between different windows 
    5, Cors solves cross-domain 
    6, Window.name utilizes the characteristics of browsers to achieve different domains transfer of data between

29. How to optimize webpack packaging speed?

1. Reduce the use of loaders on templates as much as possible, and reduce the frequency of frequent execution of loaders. 
2. Keep up with the iteration of development technologies: node, yarn, npm, and webpack keep the latest and most stable versions. 
3. Plugins should be as few and reliable as possible, and select performance Well, the official recommended plug-in 
4. Reasonable configuration of Resolve parameters 
5. Use DllPlugin to increase the packaging speed of webpack 
6. Control the size of package files 
7. Thread-loader, parallel-webpack, happypack multi-process packaging

30. How to solve the slow loading speed of the first screen of SPA?

First-screen loading: the time from when the browser responds to the URL input by the user to when the first-screen content is rendered. At this time, the entire webpage does not necessarily have to be rendered completely, but it needs to display the content required by the current window. 1. Reduce the size of the entry file 
    :, Divide the components corresponding to different routes into different code blocks. When the route is requested, the route will be packaged separately, so that the entry file becomes smaller and the loading speed is greatly increased 
    . Worker offline caching, reasonable use of localstroage 
    3, UI framework loading on demand 
    4, repeated packaging of components 
    5, compression of image resources 
    6, enabling GZip compression 
    7, using SSR: server-side rendering, components or pages generate html strings through the server, and again send to browser

31. How many modes does react router have? Implementation principle?

Two modes: hash mode and history mode 
    Hash principle: when the hash value changes, the hashchange event on the global window object is triggered. So the hash mode routing is to use the hashchange event to monitor the change of the URL, so as to perform DOM operations to simulate the page jump 
    History principle: use the new pushState () and replaceState () methods in the HTML5 History Interface.

32. What are the steps from inputting url in the address bar of the browser to displaying the page?

1. The browser submits the requested URL to the DNS domain name analysis, finds the real IP, and initiates a request to the server; 
2. The server returns the data after the background processing is completed, and the browser receives the file (HTML, JS, CSS, images, etc.) 
3 . The browser parses the loaded resources (HTML, JS, CSS, etc.) and establishes the corresponding internal data structure (such as HTML DOM); 4. Load the parsed resource 
files, render the page, and complete.

33. Tell me about the data types in JavaScript? Storage difference?

Basic types: number, string, Boolean, undefined, null, symbol 
Complex types: object, array, function 
Storage differences: 
    1. Different locations: basic data types are stored on the stack, and reference types are stored on the heap. 
    2. Declaration Memory address allocation for variables: the corresponding value is stored in the value stack of simple type, and the memory address pointing to the heap is stored in the stack of reference data type 3. The assignment of simple basic type generates the same value, and the two objects correspond to 
    different Address, complex type assignment assigns the memory address of the saved object to another variable, and the two variables point to the same object in the heap memory

34. Tell me about your understanding of React Hooks? What problem did it solve?

Hooks are a new feature in React 16.8. It allows you to use state and other React features without writing classes 
to solve problems: 
    1. It is difficult to reuse and share state-related logic in components 
    2. Due to business changes, function components have to be changed to class components 
    3. Components with complex logic are difficult to develop and maintain. When a component needs to deal with multiple irrelevant local states, each life cycle function may contain various unrelated logic. 4. Class 
    components are optimized based on existing tools Some existing problems 
    5. The emergence of hooks has expanded the functions of function components and has similar functions to class components. In our daily use, using hooks can solve most problems, and also has a code reuse mechanism, so Prioritize hooks

35. Tell me about your understanding of promises?

    1、Promise是最早由社区提出和实现的一种解决异步编程的方案,比其他传统的解决方案(回调函数和事件)更合理和更强大。
    2、promise是为解决异步处理回调金字塔问题而产生的
    3、Promise对象的状态不受外界影响,Promise的状态一旦改变,就不会再变,任何时候都可以得到这个结果,状态不可以逆,只能由 pending变成fulfilled或者由pending变成rejected
    4、Promise构造函数接受一个函数作为参数,该函数的两个参数分别是resolve和reject。它们是两个函数,由 JavaScript 引擎提供,不用自己部署。resolve函数的作用是,将Promise对象的状态从“未完成”变为“成功”(即从 pending 变为 resolved),在异步操作成功时调用,并将异步操作的结果,作为参数传递出去;reject函数的作用是,将Promise对象的状态从“未完成”变为“失败”(即从 pending 变为 rejected),在异步操作失败时调用,并将异步操作报出的错误,作为参数传递出去。
    5、Promise实例生成以后,可以用then方法分别指定resolved状态和rejected状态的回调函数。

36、 说说webpack中常见的Loader?解决了什么问题?

1、loader 用于对模块的源代码进行转换,在import或加载模块时预处理文件
2、Style-loader:将css添加到DOM的内联样式标签style中
3、Caa-loader:将css文件通过require的方式引入,并且返回css代码
4、Less-loader:处理less
5、Sass-loader:处理sass
6、Postcss-loader:处理postcss来处理css
7、File-loader:分发文件到output目录并返回相对路径
8、Html-minify-loader:压缩html

37、说说 React 性能优化的手段有哪些?

1、通过shouldComponentUpdate:对比state和props,确定是否重新渲染,默认返回true,不希望渲染返回false
2、PureComponent:通过对比state和props间比较结果来实现
3、React.memo:缓存组件的渲染,避免不必要的更新(只能用于函数组件)
4、避免使用内联函数:每次调用render时就会重新渲染一个新的函数,在组件内部创建一个函数,将事件绑定到该函数本身
5、使用React Fragments避免额外标记
6、使用Immutable:减少渲染的次数
7、懒加载组件:使用suspense和lazy组件实现代码拆分功能
8、事件绑定方式
9、服务端渲染

38、 说说 React中的setState执行机制?

    The display form of a component can be determined by the data state and external parameters, and the data state is the state. When the state of the value needs to be modified, it is changed through seState, so as to achieve the function of updating the internal data of the component. SetState can be divided into synchronization and update data 
    . Asynchronous update, in component life cycle or react synthesis event, setState is asynchronous, in setTimeout or native dom event, setState is synchronous

39. What are the communication methods between Vue components?

This type of question is first classified to show that you know more about it, so I didn’t finish it or missed it. The interviewer doesn’t care about the four major 
categories 
of component communication. Parent and child and parent and child. Understanding 
1. props and $emit Parent components pass data to child components through props, and child components pass data to parent components through $emit to trigger events 
2. $attrs and $listeners 
3. The two methods above the central event bus bus It deals with data transfer between parent and child components, but what if the two components are not parent-child? In this case a central event bus approach can be used. Create a new Vue event bus object, then trigger the event through bus.$emit, and listen to the triggered event through bus.$on. 
4. Provide and inject Variables are provided through provider in the parent component, and then variables are injected through inject in the child component. No matter how deep the subcomponent is, as long as inject is called 
, the data in the provider can be injected. Instead of being limited to only get data from the prop attribute of the current parent component, as long as it is within the life cycle of the parent component, the child component can call it. 
5. v-model: When the parent component passes the value to the child component through v-model, it will automatically pass a prop attribute of value, and automatically modify the v-model binding in the child component through this.$emit('input', val) Set the value 
6, $parent and $children 
talk about the role of the Key value in vue 
talk about the virtual dom and diff algorithm in vue 
7, boradcast and dispatch
8. Vuex handles data interaction between components. If the business logic is complex and many components need to process some common data at the same time, the above methods may not be conducive to project maintenance at this time. The approach of vuex is to use these public data The data is extracted, and then other components can read and write this public data, so as to achieve the purpose of decoupling.

40. Tell me about the pitfalls in the React life cycle? How to avoid it?

1. getDerivedStateFromProps is easy to write anti-pattern code, which makes the distinction between controlled components and uncontrolled components blurred. 
2. componentWillMount has been deprecated in React and is not recommended. The main reason is that the new asynchronous architecture will cause it to be used more calls, so network requests and event bindings should be placed in componentDidMount 
3. componentWillReceiveProps is also marked as deprecated and replaced by getDerivedStateFromProps, mainly due to performance issues. 
4. shouldComponentUpdate determines whether a new rendering needs to be triggered by returning true or false. Mainly used for performance optimization. 
5. componentWillUpdate is also marked obsolete due to the new asynchronous rendering mechanism, and is not recommended. The original logic can be combined with getSnapshotBeforeUpdate and componentDidUpdate for transformation. 
6. If you forget to unbind the event in the componentWillUnmount function, cancel the timer and other cleaning operations, it is easy to cause bugs. If no error boundary handling is added, when an exception occurs in rendering, the user will see an inoperable white screen, so be sure to add

41. What does setState do in the reconciliation phase?

1. After calling the setState function in the code, React will merge the incoming parameter object with the current state of the component, and then trigger the so-called reconciliation process (Reconciliation). 
2. After the reconciliation process, React will construct the React element tree according to the new state in a relatively efficient way and start to re-render the entire UI interface; 3. After 
React gets the element tree, React will automatically calculate the new tree and the old tree. Node differences, and then minimize the re-rendering of the interface according to the differences; 
4. In the difference calculation algorithm, React can relatively accurately know which positions have changed and how they should be changed, which ensures on-demand updates instead of all new render.

42. Talk about the realization principle of redux, and write the core code?

1. Put the state of the application into the state, and the store manages the state. 
2. The role of the reducer is to return a new state to update the corresponding state in the store. 
3. According to the principle of redux, every state change of the UI layer should be triggered by an action. The action is passed to the corresponding reducer, and the reducer returns A new state updates the state stored in the store, thus completing a state update 
4. subscribe is to subscribe the listener function for the store, and these subscribed listener functions are executed sequentially after each dispatch is initiated. 
5. Middleware can be added Rewrite the submitted dispatch

43. What is the principle of React synthetic event?

    The events in react are all synthetic events. Instead of binding every dom event to the dom, the event is bound to the document uniformly. When triggered, the event bubbles to the document to trigger the synthetic event, because it is a synthetic event , so we can't use e.stopPropagation to stop, but use e.preventDefault to stop. 
    Synthetic event: Loop all types of eventPlugins, generate different event pools corresponding to each event type, if it is empty, generate a new one, use the previous one, get the specified callback function according to the unique key, and return with Callback function for parameters.

44. Why do react elements have a $$type attribute?

The purpose is to prevent XSS attacks. 
    Because Synbol cannot be serialized, React can determine whether the current element object is from the database or generated by itself through whether there is a $$typeof attribute. If there is no $$typeof attribute, react will refuse to process the element.

45. Tell me about your understanding of redux middleware? What are the commonly used middleware? Implementation principle?

    Redux middleware is a type of software between the application system and system software. It uses the basic services provided by the system software to connect various parts of the application system or different applications on the network to achieve resource sharing and function sharing. Commonly 
used Middleware: redux-thunk is used for asynchronous operations, redux-logger is used for log records 
Implementation principle: all middleware are put into an array for nested execution, judge the data type passed in, and finally execute store.dispatch, middleware The internal middleware API can get the getstate and dispatch methods. 

46. ​​Tell me about your understanding of the event loop?

JavaScript is a single-threaded language, which means that only one thing can be done at the same time, but it does not mean that single-threaded is blocking, and the way to achieve single-threaded non-blocking is the event loop. All 
tasks are divided into synchronous tasks. , Asynchronous tasks. 
    Synchronous tasks: Tasks that are executed immediately. Synchronous tasks generally enter the main thread directly for execution. 
    Asynchronous tasks: Ajax network requests, setTimeout timer function 
    synchronous tasks enter the main thread, that is, the main execution stack, and asynchronous tasks enter the task queue. If the task in the main thread is empty after execution, it will go to the task queue to read the corresponding task and push it to the main thread for execution. Then the continuous repetition of the above process is called the event loop.

47. Front-end cross-domain solution?

1. Jsonp cross-domain: There is no cross-domain restriction using the script tag, the src attribute sends a get request with a callback parameter, the server interface returns the data and puts it into the callback function, returns it to the browser, the browser parses and executes it, and gets it from the front end Data 
2. Cross-domain resource sharing: Allow browsers to send XMLhttpRequest requests to cross-origin servers, overcoming the limitation that ajax can only be used on the same origin 
3. Nginx proxy cross-domain 
4. Node.js middleware proxy cross-domain 
5. Localtion.hash +iframe cross domain

48. Common methods and functions of arrays, at least 15?

1. Array.join(): Join the elements in the array into a string 
2. Array.push(): Append the new element to the last position of the array 
3. Array.splice(): According to the subscript of the array Add or delete elements at any position in the array. The formal parameter 1 means to add or delete from the number of elements according to the subscript of the array. 
4. Array.slice(): Cut out a new array according to the array subscript 
5. Array.forEach(): This array method receives three formal parameters, the first formal parameter is each item in the array; The second parameter is the index subscript of each item in the array; the third parameter is the array itself. 
6. Array.map(): Loop, allocate memory space to store a new array and return 
7. Array.filter(): Create a new array, the elements in the new array are checked by the filter method and then specified in the array to meet the conditions all elements and it doesn't change the original array. 
8. Array.reduce(): Receive a function as an accumulator (accumulator), each value in the array (from left to right) starts to reduce (increment), and finally becomes a value. 
9. Array.every(): Checks whether all array values ​​pass the test. 
10. Array.some(): Checks whether some array value passes the test 
11. Array.indexOf(): Searches for an element value in the array and returns its position 
12. Array.find(): The first array that passes the test function The value of the element 
13, Array.pop(): delete the last element from the array 
14, Array.shift(): delete the first array element, and shift all other elements to a lower index
15. Array.unshift(): Add new elements to the array at the beginning and reversely shift the old elements

49. Tell me about your understanding of mixin in vue?

1. Mixin is a class in an object-oriented programming language, which provides method implementation. Other classes can access the method of mixin without becoming its subclass. 2. Mixin in Vue is 
a very flexible way to distribute Vue The reusable function of the component 
3. It is essentially a js object, which can contain any function options in the component, such as data, components, methods, created, etc. 
4. Pass the shared function into the mixins option in the form of an object, When a component uses a mixins object, all the options of the mixins object will be mixed into the options of the component itself.

50. What is the difference between for...in loop and for...of loop?

1. Both For in and for of can be used to traverse 
2. For in traverses the index index of the array; for of traverses the element value of the array 
3. For in is more suitable for traversing objects, of course it can also traverse arrays, but There will be some problems; for of can traverse numbers, array objects, strings and other collections with iterator objects 
4. For in will traverse all enumerable properties of the array, including prototypes; For of traverses only the elements in the array, Does not include prototype attributes and indexes 
5. For in always gets the key of the object or the subscript of the array or string; for of gets the value of the object or the value of the array or string

51. What are the ways to judge Js data type? Name at least 5? What's the difference?

1. Typeof method: returns a string representing the data type, regardless of the type of the referenced object, returns Object 
2. Instanceof method: determines the data type from the construction type 
3. Constructor method: is an attribute on the prototype object, pointing to the constructor 
4. Object.prototype.toString method: the object object returns [Object object], other types need call, apply to call 
5. Jquery.type() method

52. Tell me about your understanding of Object.defineProperty()?

    1. The Object.defineProperty() method will directly define a new property on an object, or modify an existing property of an object, and return this object. IE8 is not compatible. 
    2. There are currently two types of attribute descriptors in an object: data descriptors and access descriptors. 
    3. A data descriptor is an attribute with a value, which can be written or not; access descriptors are defined by get 4. The data descriptor 
    has value and writeable, and the access descriptor is an attribute described by a bunch of getter and setter functions. The get return value is used as the attribute value, and the set method accepts the only parameter. And assign the new value of the parameter to the attribute 
    5. When using the get or set method, the writable and value attributes cannot be used, and vice versa

53. What are the application scenarios for the understanding of custom instructions in Vue?

1. The instruction system is also the language system of computer hardware, also called machine language, which is the main attribute of the computer seen by system programmers. 2. 
Custom instructions also exist as hook functions like components, bind, inserted, update, componentUpdated, unbind 
3 , Scenario: prevent repeated submission of forms, lazy loading of pictures, one-click copy function

54. Talk about several situations of javascript memory leaks?

1. Unexpected global variable 
2. Forgot to release the timer 
3. Multiple references, when multiple variables refer to the same object, some references are not cleared 
4. Unreasonable use of closures 
5. Console.log print information memory not released

55. How to resume uploading of large files?

When uploading large files, variables such as the server's ability to process data, request timeouts, and network fluctuations will affect our user experience, so we need to do separate processing for large file uploads 
. The uploaded file, according to a certain size, divides the entire file into multiple data blocks for uploading in pieces. After the upload is completed, the server summarizes and integrates the uploaded files into the original file. 2. Breakpoint resume: 
break Click Resume refers to divide the downloading or uploading task into several parts when downloading or uploading again, and each part uses a thread to upload or download. Or the downloaded part starts to continue uploading or downloading the unfinished part, and there is no need to start uploading and downloading from the beginning, the user can save time and increase the speed. 
3. There are generally two implementation methods for resuming uploads from breakpoints. The server returns and tells where to start; the browser handles it by itself.

56. How does native js implement pull-up loading and pull-down refresh?

Both pull-up loading and pull-down refresh depend on user interaction 
1. Pull-up loading: 
    1. scrollTop: The height of the scrolling window is the distance from the top of the window. It will increase as you scroll up. The initial value is 0, which is a Changing value 
    2. clientHeight: It is a fixed value, indicating the height of the visible area of ​​the screen; 
    3. scrollHeight: It also exists when the page cannot be scrolled. At this time, scrollHeight is equal to clientHeight. 4. scrollHeight represents the total length of all elements of the body (including the padding of the body element itself), 
a bottoming formula: scrollTop + clientHeight >= scrollHeight 
2. Pull-down refresh: 
the essence of pull-down refresh is that when the page itself is placed at the top, the user needs to pull down Triggered actions 
    1. Listen to the native touchstart event, record its initial position value, e.touches[0].pageY; 
    2. Listen to the native touchmove event, record and calculate the difference between the current sliding position value and the initial position value, greater than 0 means pull down, and use the translateY attribute of CSS3 to make the element follow the gesture to slide down the corresponding difference, and also set a maximum value allowed to slide; 3. Listen to the 
    native touchend event, if the element slides to the maximum value at this time , the callback is triggered, and translateY is reset to 0 at the same time, and the element returns to the initial position

57. Tell me about the difference between device pixels, css pixels, device independent pixels, dpr, and ppi?

1. In the case of no scaling, 1 CSS pixel is equal to 1 device independent pixel 
2. The device pixel does not change after it is produced by the screen, but the device independent pixel is a virtual unit that will change 
3. On the PC side, 1 device Independent pixel = 1 device pixel (at 100%, unscaled) 
4. In the mobile terminal, 1 device independent pixel = 1 device pixel under the standard screen (160ppi) 
5. Device pixel ratio (dpr) = Device pixels/device independent pixels 
6. Pixels per inch (ppi), the larger the value, the clearer the image

58. Tell me about your understanding of BFC?

1. Bfc is a block-level formatting context. It is a rendering area in the page and has its own set of rendering rules. 2. The 
purpose of Bfc is to form a completely independent space from the outside world, so that internal sub-elements will not Affects external elements 
3. Bfc is an isolated and independent container on the page. The child elements inside the container will not affect external elements, and vice versa. 
4. The area of ​​Bfc will not overlap with the area of ​​floating elements

59. Tell me why TCP needs a three-way handshake and a four-way handshake?

The three-way handshake is to establish a reliable data transmission channel, and the four-way handshake is to ensure that the connection is closed after the data is received. 
1. The three-way handshake means that when a TCP connection is established, the client and the server need to send a total of three packets. The main function is to confirm whether the acceptance and sending capabilities of both parties are normal, and specify their own initialization sequence for the subsequent reliable transmission. Preparation 
2. Waving four times means that tcp terminates a connection, which requires four waved hands. When the server receives the disconnection message from the client, it will not close the connection immediately, but will first send an ACK packet to tell the client After receiving a request to close the connection, the connection will only be disconnected after all the messages from the server have been sent

60. What are the means of front-end performance optimization?

1. Resources are compressed and merged to reduce http requests. 
2. Images are optimized, using png to make them smaller in size. 
3. Non-core codes are loaded asynchronously. 
4. Using browser cache, resource files are stored locally, and the next call can be taken directly from the cache. 
5. CDN can be used Distribute load and improve performance 
6. DNS pre-analysis 
7. Enable Gzip code compression 
8. Reduce unnecessary cookies

61. At least three ways to clear the floating front end?

1. Extra label method: put an empty div in front of the floating element that needs to be cleared, and set the attribute clear for this empty div: both 2. Set the overflow attribute for the 
parent element to hidden or auto 
3. :after Use pseudo-elements to clear all Floating label -> add a block-level element in front of the floating label

62. What are strong caching and negotiation caching?

After the browser requests a resource for the first time, when it needs to request again, the browser will first obtain the header information of the resource cache, and then judge whether the resource has expired in the local cache according to Cache-Control and expires. If it has not expired, the resource information will be obtained directly from the local cache, and the browser will no longer re-request the resource from the server. If it expires, it will need to resend the request, re-cache the resource, and update the cache time. 
1. Strong caching is controlled by the Expires and Cache-Control fields in the http request header, which are used to indicate the cache time of resources. Expires is the specification of http1.0, and its value is an absolute time string in GMT format. 
2. The negotiation cache is used by the server to determine whether the cache resource is available and expired. Because the server needs to confirm to the browser whether the cache resource is available, the two need to communicate, and the communication process is to send a request, so there needs to be a special identifier in the header to let the server confirm whether the requested resource can be cached and accessed

63. Tell me about your understanding of stacks and queues? Application scenario?

1. Stack (stack), also known as stack, is a linear table with limited operations. It is limited to a linear table that only performs insertion and deletion operations at the end of the table. 2. The stack 
stores data according to the principle of first in, last out, and the data that enters first It is pushed into the bottom of the stack, and the last data is on the top of the stack. When the data needs to be read, the data will be popped from the top of the stack, which has a memory function. 3. The queue is 
very similar to the stack. The queue is a special linear table. The special feature is that It only allows delete operations at the front end of the table (front), and insert operations at the back end (rear) 
of the table. It is first deleted from the queue, so the queue is also called first-in-first-out 
5. Scenario: the stack can be used in function calls and recursion, and when the compiler analyzes the input syntax; the queue can be used when traversing a binary tree

64. Tell me about your understanding of git rebase and git merge? the difference?

1. In a project using git for version management, when the development of a feature is completed and merged into the master branch, there will be two ways: git merge and git rebase 2. Both git rebase and git merge have the same 
effect , both merge the submission of one branch into another branch, but the principle is different 
3. git merge merges the current branch into the specified branch: git merge xxx; git rebase merges the branch or merges into the specified commit: git rebase -I <commit> 
4. Merging branches through merge will add a merge commit, and then link the history of the two branches; rebase will move the entire branch to another branch, effectively integrating all branches. submit

65. Tell me what are the commonly used commands of git?

1. git status: keep track of the current status of the warehouse, whether any changes have been made 
2. git diff novel.txt: view the modified content operation 
3. git reflog: view the version number 
4. git log: view the submission history 
5. git reset --hard version number: Shuttle to that version number 
6. git checkout -- novel.txt: You can discard the modification of the workspace 
7. rm file name: delete the file (file that has not been submitted to the workspace) 
8. git rm file name : Delete files in the repository 
9, git branch dev : Create a dev branch 
10, git branch -a : View the branch and which branch it is currently in 
11, git checkout dev : Switch to the dev branch 
12, git merge dev: Merge the current branch with dev branch to merge

66. Vue component communication?

Component communication means that the sender transmits information to the receiver in a certain format through a certain medium to achieve a certain purpose 
classification: communication between parent and child components, communication between sibling components, communication between grandparents and descendants Communication, communication between non-relational components 
There are 8 conventional communication schemes in vue: 
    1. Passing through props: the subcomponent sets the props attribute, defines the parameters passed by the receiving parent component, and the parent component passes the literal in the use of the subcomponent tag 2. Trigger a 
    custom event through $emit: the child component triggers a custom event through $emit, the second parameter of $emit is the passed value, and the parent component binds the listener to get the parameter passed by the child component 
    3 , Use ref: The parent component sets ref when using the child component, and the parent component obtains data by setting the child component ref 
    4. EventBus: Create a central event bus EventBus, and the sibling components trigger custom events through $emit, $emit second The first parameter is the value passed. 
Another sibling component listens to custom events through $on 
    5, $parent or $root: build a communication bridge through the common ancestor $parent or $root 
    6, attrs and listeners: set batch down attribute $ attrs and $listeners, which contain attribute bindings (except class and style ) that are not recognized (and picked up) as props in the parent scope. Internal components can be passed in through v-bind="$attrs" 
    7. Provide and Inject: define the provide attribute in the ancestor component, return the passed value, and receive the value passed by the component through inject in the descendant component 
    8. Vuex: the function is equivalent to A container for storing shared variables

67. Tell me about your understanding of vuex? Write the core code of its principle?

Vuex is a state management pattern + library developed specifically for Vue.js applications. It uses a centralized storage to manage the state of all components of the application, and uses corresponding rules to ensure that the state changes in a predictable manner. 
Five core attributes of vuex: state, getter, mutation, action, module 
    1, state: store data, store state; after registering the store in the root instance, use this.$store.state to access; corresponding to the data in vue; store The data mode is responsive, and the vue component reads data from the store. If the data changes, the component will be updated accordingly. 
    2. Getter: It can be considered as a computed property of the store. Its return value will be cached according to its dependencies, and will only be recalculated when its dependent values ​​change. 
    3. Mutation: The only way to change the state in Vuex's store is to submit a mutation. 
    4. action: contains any asynchronous operation, and indirectly changes the state by submitting a mutation. 
    5. module: divide the store into modules, each module has state, mutation, action, getter, and even nested submodules.

68. What are the similarities and differences between props and state? Under what circumstances will the render method be executed?

Differences: 
1. props cannot be modified inside the component, but the state can be modified inside the component 
2. The props of the self-component can be modified from the parent component, but the state of the self-component cannot be modified from the parent component. 
The same points: 
1. props and state Both are raw data exported to HTML. 
2. Both props and state are deterministic. If the component we write is a combination of the same props and state 3. Generate different outputs, then we must have done something wrong 
4. Both props and state will trigger rendering updates 
5 Both .props and state are pure JS objects (use typeof to judge, the result is object) 6. 
Under what circumstances 
can the initial value of props and state be executed from the parent component ? 
    1. When the class component calls setState to modify the state 
    2. When the function component modifies the state through useState Hook 
    3. When the class component is re-rendered 
    4. When the function component is re-rendered

69. What are the two new hook functions in react? What is the difference with the deleted will series?

Two new life cycle hook functions in React? 
1. 
The function of getDerviedStateFromProps: Get the derived state from props 
2. 
The function of getSnapshotBeforeUpdate: Get a snapshot before the component is updated, generally used in combination with componentDidUpdate, the return value in getSnapBeforeUpdate will be passed to componentDidUpdate as the third parameter, 
and componentDidUpdate will sandwich the render in the middle, In fact, its core function is to record the dom information before the update and pass it to componentDidUpdate before the render changes the dom. 
2. Hook function removed by React’s new life cycle? 
1. componentWillMount 
2. componentWillReceiveProps 
3. componentWillUpdate 
Summary 
    1. Things that may need to be done in componentWillMount (some data initialization operations should be handled in this hook), constructor and componentDidMount can also be done, or even better, this method was scrapped. 
    2. The actual behavior of componentWillReceiveProps does not match the name, because it has been replaced by getDerivedStateFromProps due to instability; 
    3. For the same reason, componentWillUpdate is replaced by getSnapshotBeforeUpdate

70. What are the characteristics and significance of CDN?

1. CDN means content distribution network, which is an intelligent virtual network based on the existing network, distributed on edge servers all over the world. The basic idea is to avoid bottlenecks and links on the Internet that may affect the speed and stability of data transmission, so as to make content transmission faster and more stable. 
2. CDN means copying data from the original server to other servers. When users visit, they can do so on servers that replicate the data content. Its purpose is to enable users to obtain the content they need faster and better, solve network congestion, and improve the response speed of users visiting websites. CDN acceleration is low in cost and fast in speed, and is suitable for websites with a relatively large number of visits. 
Features: 
1. Local cache acceleration: Improves the access speed of enterprise websites (especially websites containing a large number of pictures and static pages), and greatly improves the stability of the above websites. 
2. Mirror service: Eliminate the impact of interconnection bottlenecks between different operators, realize cross-operator network acceleration, and ensure that users of different networks can obtain good access quality. 
3. Remote acceleration: remote access users intelligently and automatically select cache servers based on DNS load balancing technology, and select the fastest cache server to accelerate remote access. 
4. Bandwidth optimization: Automatically generate the remote mirror cache server of the server. When remote users access, they can read data from the cache server, reduce the bandwidth of remote access, share network traffic, and reduce the load on the original WEB server. 
5. Cluster anti-attack: Widely distributed CDN nodes and intelligent redundancy mechanism between nodes can effectively prevent hacker intrusion, reduce the impact of various DDoS attacks on the website, and ensure better service quality at the same time.

71. What is a closure and what is the application scenario?

1. A closure is a function that can read the internal variables of other functions. To put it bluntly, a closure is a function, but it is inside other functions. 
2. In javascript, only sub-functions inside a function can read local variables, so closures can be simply understood as "functions defined inside a function". Application scenarios: 1. Imitate block-level scope 
: 
    timer 2. Buried point 
    counter: some commonly used data collection methods for products 
    3. Currying: a method of converting a multi-parameter function into a single-parameter function

72. Tell me about your understanding of the browser kernel?

The core is mainly divided into rendering engine and js engine 
1. Rendering engine: responsible for obtaining the content of the web page (HTML, XML, images, etc.), organizing information (such as css), and calculating the display method of the web page, and then outputting to the monitor or printer. Different browser kernels have different syntax interpretations for web pages, so the rendering effects are also different. All web browsers, email clients, and applications that need to edit and display network content require kernel 
2, JS engine: parsing and executing JavaScript to achieve dynamic effects on web pages 
At first, the rendering engine and the js engine were not clearly distinguished , later the js engine became more and more independent, and the kernel tended to refer only to the rendering engine

73. How many ways to clear the float? Pros and cons of each?

Clear floating: In order to solve the problem of the inner height of the parent element collapsing due to the floating of the child element 
Method: 
1. Extra label method (after the last floating label, add a new label and set clear:both for it;) Advantages: Popular Easy to understand and more convenient; Disadvantage: Add meaningless tags, poor semantics 
2. Add overflow attribute to the parent (add overflow: hidden to the parent element) Advantage: The code is concise; Disadvantage: When the content increases, it is easy to cause the content to be hidden without automatic line break 3. Use the after pseudo- element 
to clear the float. Advantages: It conforms to the idea of ​​closed floating, and the structural semantics are correct; Disadvantage: IE6-7 does not support pseudo-elements 
4. Use the before and after double pseudo-elements to clear the float. Advantages: The code is more concise; disadvantage: use zoom: 1 to trigger haslayout

74. If you need to write animation manually, how long do you think the minimum time interval is, and why?

The default frequency of most monitors is 60Hz, that is, refresh 60 times per second, so the theoretical minimum interval is 1/60*1000ms = 16.7ms. For browser rendering and user experience, the minimum setting of 0.1-0.3s is the best

75. Tell me about the difference between Real DOM and Virtual DOM? Advantages and disadvantages?

1. Real DOM, real DOM, means Document Object Model, which is an abstraction of structured text. Every node rendered on the page is a real DOM structure. 2. Virtual Dom, which essentially exists in the form of JavaScript 
objects 3. The purpose of 
creating a virtual DOM is to better render the virtual nodes into the page view. The nodes of the virtual DOM object correspond to the properties of the real DOM one by one. 4. The difference between the two is as follows: the virtual DOM 
does 
    not Perform typesetting and redrawing operations, and the real DOM will frequently rearrange and redraw 
    the total loss of the virtual DOM is "virtual DOM addition, deletion and modification + real DOM difference addition, deletion and modification + typesetting and redrawing", the total loss of the real DOM is "real DOM Complete additions, deletions and modifications + typesetting and redrawing" 
advantages and disadvantages? 
    Advantages of real DOM: easy to use 
    Disadvantages: 
        1. Low efficiency, slow parsing speed, high memory usage 
        2. Poor performance: Frequent operation of real DOM may easily lead to redrawing and reflow 
    The advantages of using virtual DOM are as follows: 
        1. Simple and convenient : If you use the real DOM to complete the page manually, it is cumbersome and error-prone, and it is also difficult to maintain in large-scale applications. 2. Performance 
        : Using Virtual DOM can effectively avoid frequent updates of the real DOM number and reduce multiple redraws 3. Cross - 
        platform: With the help of virtual DOM, React brings cross-platform capability, and a set of code runs on multiple terminals. 
    Disadvantages: 
        1. In some applications with extremely high performance requirements, virtual DOM cannot be targeted for extreme optimization
        2. When rendering a large amount of DOM for the first time, due to the calculation of an additional layer of virtual DOM, the speed is slightly slower than normal

76、说说react的事件机制?

1、react自身实现了一套自己的事件机制,包括事件注册、事件的合成、事件冒泡、事件派发等,虽然和原生的是两码事,但也是基于浏览器的事件机制下完成的。
2、React 上注册的事件最终会绑定在document这个 DOM 上,而不是 React 组件对应的 DOM(减少内存开销就是因为所有的事件都绑定在 document 上,其他节点没有绑定事件)
3、React 自身实现了一套事件冒泡机制,所以这也就是为什么我们 event.stopPropagation()无效的原因。
4、React 通过队列的形式,从触发的组件向父组件回溯,然后调用他们 JSX 中定义的 callback
5、React 有一套自己的合成事件 SyntheticEvent

77、说说你对fiber架构的理解?解决了什么问题?

React Fiber is a major change and optimization that Facebook has made to React in more than two years. It is a reimplementation of the core algorithm of React. 
In react, the following operations are mainly done: 
    1. The priority is increased for each task, and tasks with high priority can interrupt tasks with low priority. Then re-execute the low-priority tasks again. 
    2. Add asynchronous tasks and call requestIdleCallback api. When the browser is idle, 
the dom diff tree becomes a linked list. One dom corresponds to two fibers (a linked list), corresponding to Two queues, both of which are to find the interrupted task and re-execute 
    3. From the perspective of architecture, Fiber is a rewrite of the core algorithm of React (that is, the reconciliation process) 
    4. From the perspective of coding, Fiber is the internal A defined data structure, which is the node unit of the Fiber tree structure, which is the virtual DOM under the new architecture of React 16

78. What is the principle of react diff?

1. Consistent with Vue, React introduces the concept of Virtual DOM to greatly avoid invalid Dom operations, which greatly improves the construction efficiency of our pages. The diff algorithm is to find out more efficiently by comparing the old and new Virtual DOM. The real Dom changes. 
The operation process is mainly divided into three layers: tree layer, component layer, element layer 
    1, and tree layer: the tree layer ignores the operation of cross-level movement of DOM nodes, and only compares DOM nodes at the same level. Once it is found that the node does not exist, directly delete the node and all the following sub-nodes 
    2. Component layer: When encountering the same type of component, follow the tree diff to perform hierarchical comparison. When encountering a different type of component, directly judge the different component It is a dirty component and replaces all child nodes under the component. When you know that there is no change in the virtual DOM of this component, you can use it manually. shouldComponentUpdate is used to judge whether diff is required, which further improves the efficiency and performance of diff. 3. 
    element Layer: lower than the same level, in the face of new nodes, the insertion operation can be implemented; in the face of redundant nodes, the deletion operation can be performed; in the face of transposed nodes, the movement operation can be performed

79. How to use css to realize a triangle?

1. Border: Given an element with a width and height of 0, any value of its border will intersect directly, and we can use this intersection to create a triangle. In other words, the border attribute is composed of triangles. If you want a triangle pointing to the right, you can make the left side of the border visible, and set the other sides to be transparent: 2. linear-gradient 
: linear-gradient needs to be combined with background-image to achieve Triangle, let's implement a triangle step by step using gradients. 
3. clip-path: clip-path is to use it to draw a polygon (or circle, ellipse, etc.) and position it within the element. In fact, the browser doesn't draw anything outside the clip-path, so what we see is the border of the clip-path. 
4transform: rotate with overflow: hidden to draw a triangle

80. What is the function of shouldComponentUpdate?

1. According to the return value of shouldComponentUpdate(), determine whether the output of the React component is affected by the current state or props changes. The default behavior is for the component to re-render every time the state changes. 
2. Changes in props and state values ​​in react will cause the component to re-render. Using shouldComponentUpdate is to reduce unnecessary rendering of render. Returns a Boolean value, then compares the Virtual DOM, and finds out whether a real DOM update is required

81. Tell me about your understanding of git rebase and git merge? the difference?

1. In a project that uses git to manage the version, when the development of a feature is completed and merged into the master branch, git rebase and git merge will be used. 2. Both have the same 
function: submitting a branch Merge into another branch, but the principle is different 
3. Git merge merges the current branch into the specified branch: git merge xxx; git rebase merges into the specified commit: git rebase -I <commit > 
4. The branch merged by merge A merge commit will be added, and then the history of the two branches will be linked; rebase will move the entire branch to another branch, effectively integrating the commits on all branches

82. In the process of using redux, how to prevent the constant duplication of the defined action-type?

ES6 introduces a new primitive data type Symbol, representing a unique value. 
    The new command cannot be used before the Symbol function, otherwise an error will be reported. This is because the generated Symbol is a value of a primitive type, not an object. The Symbol function can accept a string as a parameter, which represents a description of a Symbol instance, mainly for displaying on the console or converting it to a string, which is easier to distinguish .

83. Talk about the virtual dom in React? What is the relationship between diff and key during virtual dom calculation?

1. In fact, it is just a layer of abstraction to the real DOM. The tree is based on JavaScript objects (VNode nodes), and the attributes of the objects are used to describe the nodes. Finally, the tree can be mapped to the real environment through a series of operations. Creating a virtual DOM is to better render virtual nodes into the page view, so the nodes of the virtual DOM object correspond to the properties of the real DOM one by one. 2. Simulate the web document nodes through JS to 
generate a JS object tree (virtual DOM), and then Take another step to generate a real DOM tree, and then draw it to the screen. If the content changes later, React will regenerate a brand new virtual DOM tree, then compare the diff with the previous virtual DOM tree, package the difference into a patch, apply it to the real DOM, and then render it to the screen for browsing device. 
What is the relationship between diff and key when virtual dom is calculated: 
    1. React needs to maintain two virtual DOM trees at the same time: one represents the current DOM structure, and the other is generated when the React state changes and is about to be re-rendered. React compares the differences between these two trees to decide whether to modify the DOM structure and how to modify it. This algorithm is called Diff algorithm. 
    2. key When a node at the same level adds a key attribute unique to other nodes at the same level, when its position in the current level changes. After the react diff algorithm compares the old and new nodes, if it finds a new and old node with the same key value, it will perform a move operation (and then still follow the original strategy to go deep into the node to compare and update the difference), instead of deleting the old node according to the original strategy. An operation that creates a new node. This undoubtedly greatly improves React performance and rendering efficiency.

84. React's props.children uses the map function to traverse and will receive an exception display. Why? How should it be traversed?

1. If the current component has no child node data type, it is undefined. 
2. If there is a child node data type, it is object. 
3. When there are multiple child nodes, it will be an array. Only when there are multiple nodes, the map method can be called directly. React provides a react.children.map() method, which can safely traverse the child node objects.

85. Tell me about your understanding of immutable.js?

1. Immutable.js is used for performance optimization in react 
2. Using immutable in react can reduce some unnecessary rendering of the page, and it does not need to render in depth comparison like in react 
3. immutable can be directly and quickly In contrast, the rendering is completed, which improves the rendering efficiency and reduces performance consumption. 
4. Immutable is immutable. In the computer, it refers to data that cannot be changed once it is created. 
Any modification or addition or deletion of the Immutable object will be Return a new Immutable object 
The principle of Immutable implementation is Persistent Data Structure (persistent data structure): 
    1. Use a data structure to save data 
    2. When the data is modified, an object will be returned, but the new object will be updated as soon as possible. Possible use of previous data structures without wasting memory

86. Redux is originally synchronous, why can it execute asynchronous code? What is the realization principle? What is the implementation principle of middleware?

1. Redux-thunk is a middleware that supports asynchronous operations. 
2. To execute an asynchronous operation, you first need to download a thunk, and use the thunk to perform an asynchronous operation. It supports asynchronous operations. You can use dispatch and getState to obtain data or state 3 
. Redux is a state management library. The core of redux is three parts: store, actions, and reducers. 
4. Send it to the actions of the task through dispatch, return a promise object in the actions, and then send it to the reducers through dispatch. 
5. In the reducers Interpretation by passing type and data

87. What is the biggest difference between synchronous action and asynchronous action in redux?

1. Synchronous action: After the dispatch function is executed, the corresponding reducer pure function is executed immediately. After the reducer is executed, the state changes immediately. At this time, the store.getState function is used to get the latest state value; 2 
. Asynchronous action: In principle, redux does not provide a solution for asynchronous actions. Asynchronous actions need to rely on third-party middleware solutions (such as redux-thunk). After dispatching an asynchronous action (essentially a function of dispatch), the target The state does not respond immediately, but depends on the logic inside the asynchronous function to determine when the state responds. 
3. Differences: 
    First, distinguish between redux and react-redux. Redux is a separate module that can also be used in other frameworks, while react-redux is born for react to manage data. 
    The design idea of ​​redux: web application is a state machine, view and state are in one-to-one correspondence, and all states are stored in an object

88. What are the differences and usage scenarios between redux-saga and redux-thunk?

1. Using the code of redux-thunk, when we return a function, the store will call the returned function for us, and expose dispatch for us to use. For the whole process of redux-thunk, it waits for the execution of the asynchronous task to be completed, then we call dispatch, and then go to the store to call reducers 2. 
Using the code of redux-saga, when the action type of our dispatch is not in the reducer , the listener function takeEvery of redux-saga will listen to it, and execute the put method when the asynchronous task has a result, which is equivalent to dispatch, and trigger dispatch again. For the whole process of redux-saga, after the action and reducer are executed, it is judged whether there is such an action 
difference in the reducer: 
    1. The timing of redux-thunk and redux-saga processing asynchronous tasks is different. For redux-saga, compared to 2. On the basis of redux action, a branch of async action has been re-opened to handle asynchronous tasks separately. 3. 
    Saga has basically set up an asyc event monitoring mechanism by itself, and the amount of code has greatly increased. , from my own experience, redux-thunk is simpler and more closely related to redux itself.

89. Why is the ordinary for loop more efficient than the forEach loop?

1. The for loop is to repeatedly execute the code in the loop through the subscript. It has powerful functions and can obtain elements through the index. It is more convenient when dealing with more complex processing. 
2. The forEach() loop method is used to call each element of the array and pass the element to the callback function. Some foreach is also called enhanced for loop, forEach is actually a special simplified version of for loop. The forEach loop will not execute the callback function for an empty array. 
Differences: 
    1. Traversal: for loop traverses in order, forEach uses iterator iterator to traverse 
    2. Data structure: for loop accesses elements randomly, foreach accesses elements in sequential linked list 
    3. Performance: For arraylist, it is in order The table can be accessed sequentially by using the for loop, and the speed is relatively fast; using the foreach loop will be slightly slower than the for loop. For linedlist, it is a singly linked list, and the for loop needs to read the next field from the first element every time to read, which is very slow; using foreach can directly read the current node, and the data is faster.

90. What is the 1-pixel solution for the mobile terminal?

In mobile web development, set the border to 1 pixel in the UI design draft. If border: 1px appears during the front-end development process, the test will find that on some models, 1px will be thicker, which is a more classic mobile terminal. 1px pixel problem 
Solution: 
1. Decimal: 0.5px, I believe the browser will definitely support it slowly; at present, if it can be used, you can hack it; 
2. The shadow, border-img solution is not recommended to use 
3. The background image and zoom can be used together in the project, such as using zoom for a single line, and simulating the four frames with a background image. Well, if you want rounded corners, there is nothing you can do. 4. It is recommended to use 
transform and pseudo-classes

91. What is the scaling mechanism in flexbox?

1. The item setting flex-grow attribute of the flex box defines the enlargement ratio of the item. The default value is 0. The larger the value, the stronger the enlargement, and negative values ​​are not supported; 2. The flex-shrink 
attribute defines the shrinkage ratio of the item. The default value is 1. The larger the value, the stronger the reduction. Negative values ​​are also not supported; 
3. The flex-basis attribute defines the main axis space occupied by the item before allocating excess space. The browser calculates whether the main axis is redundant according to this attribute. space. His default value is auto, which is the original size of the project.

92. Tell me about your understanding of mixin in vue?

1. Mixin is a class in an object-oriented programming language that provides method implementations. Other 1 classes can access methods in mixin without being called subclasses. 2. Mixin in Vue is a reusable distribution of Vue 
components Function 
3. It is essentially a js object, which can contain any function options in the component, such as data, component, methods, created, etc. 4. 
Pass the public function into the mixins option in the form of an object. When the component uses the mixins object , all the options of the mixins object are mixed into the options of the component itself

93. What is the difference between for...in loop and for...of loop?

Both for in and for of belong to traversal 
1. The index index of the array when for in traversal, the element value of the array when for of traversal 
2, for in is more suitable for traversing objects, and can also traverse arrays, there will be some problems; for of arrays , objects and other collections with iterator objects 
3. for in always gets the key of the object or the subscript of the array or string; for of gets the value of the object or the value of the array or string

94. What is the publish-subscribe model, and write its core implementation code?

1. Publish and subscribe mode: Subscriber (Subscriber) submits the subscription event to dispatch center (Topic) through event registration (Subscribe), and dispatch center (Topic) saves the subscriber's registration information (callback function). Whenever the publisher (Publisher) publishes When an event occurs, the published message is submitted to the dispatch center through event publishing (Publish), and then the dispatch center uniformly processes the message that the subscriber registers for the event (executes the callback function when registering) 2. Implementation: //Instantiate a 
publish 
    subscription Mode, multiple new, event isolation can be achieved, normally one project is enough 
    const pub1 = new Pubsub() 
    //call example 
    pub1.topic("on-sleep) //create a sleeping subscription topic 
    //student 1 Subscribe to sleep 
    pub1.subscribe("on-sleep",(a)=>{ 
        console.log("sleep") 
        console.log(a) 
    }) 
    //Student 2 subscribes to sleep callback is different 
    pub1.subscribe("on- sleep",(a)=>{ 
        console.log("sleep2") 
        console.log(a) 
    }) 
 
    setTimeout(()=>{ 
        //The time is almost up, let them know it's time to sleep!
        pub1.publish("on-sleep",{info:"It's time to sleep!"}) 
    },2000)

95. Tell me about your understanding of the viewport?

1. In a browser, the area you see is the viewport. 
2. In the PC-side page, there is no need to distinguish the viewport, because the layout viewport and the visual viewport are the same. 
3. But in mobile On the mobile terminal, the viewport of your layout is different from the visible viewport because the webpage window on the mobile terminal is often relatively small, and we may hope that a large webpage can be completely displayed on the mobile terminal; 4. So by default, the 
mobile The layout viewport of the terminal is larger than the visual viewport 
5, so on the mobile terminal, we divide the viewport into three situations 
    : 1. Layout viewport (layout viewport) 
    2. Visual viewport (visual layout) 
    3. Ideal viewport (ideal viewport) layout)

96. Tell me about your understanding of useEffect, which life cycles can be simulated?

1. Use the hook function useEffect to realize the side effects of components. useEffect(desired action, [list of component states]); The second parameter is used to process the timing of useEffect calls, which is an array, and the array is a list of component states. 
2. useEffect simulates componentDidMount: when the second parameter of useEffect is passed in an empty list, it is equivalent to simulating the lifecycle function componentDidMount. This side effect is only called once when the component mounts the ui for the first time. Use it to simulate when the component is mounted for the first time, access the api, and obtain data: 
3. UseEffect simulates componentDidUpdate: If you do not bring the second parameter when using useEffect, it is equivalent to simulating the lifecycle function componentDidUpdate. Will be called every time the rendering finishes. 
4. useEffect simulates componentWillUnmount, and returns a function in useEffect to simulate component WillUnmount

97. Talk about the difference between setState and replaceState in React?

1. setState is used to set the state object 
2. Two parameters: nextState, the new state to be set, which will be merged with the current state; callback, optional parameter, callback function. This function will be called after setState is successfully set and the component is re-rendered. 
3. Merge nextState and current state, and re-render the component. setState is the main method for triggering UI updates in React event handlers and request callbacks. 
4. The replaceState() method is similar to setState(), but the method will only retain the state in nextState, and the original state that is not in nextState will be deleted. 5. 
Two parameters: nextState, the new state to be set, which will replace the current state state. callback, optional parameter, callback function. This function will be called after replaceState is successfully set and the component is re-rendered. 
​--------------------------------------------------
---------------------- 
1. setState is to modify part of the state, which is equivalent to Object.assign, just overwrite and will not reduce the original state; 
2. replaceState is to completely replace the original state, which is equivalent to assigning a value, replacing the original state with another object. If the attributes of the new state are reduced, then the state will no longer exist in the state.

98. Talk about the working principle of onClick binding in react?

After the component element is bound to the onClick event: 
1. React will first register the event, and register the event to the document uniformly. 
2. Store the event function according to the unique representation key of the component. 
3. Unified designation, dispatchEvent callback function 
4 . Storage event callback: react will store the click event in an object. The storage in the callback function is stored in the object in the form of a key-value pair. The key is the unique identifier id of the component, and the event corresponding to the value is the callback function. Through the component The key can return to the corresponding function.

99. What is vertical margin consolidation? Tell me about the situation after the merger?

1. Merge vertical margins: when two margins meet, a margin will be formed, and the height of the merged margin is equal to the larger of the heights of the two merged margins. 2. Note: Only 
normal Only the vertical margins of block-level elements in the document flow will be merged, and the margins between inline boxes, floating boxes or absolute positioning will not be merged. Situations: 1. When the vertical margins of adjacent elements are 
merged 
: If the upper element has a lower margin and the lower element has an upper margin, then the vertical spacing between them is not the sum of bottom and top, but the larger of the two. This phenomenon is called outer margin. Collapse 
2. When the vertical margins of nested block elements are merged: if the parent element has no top padding and border, then the top margin of the parent element will merge with the top margin of the child element, and the merged margin will be the middle of the two The larger one, that is, the upper margin of the parent element is 0, and it will also be merged. 
Solution: You can define a 1-pixel upper border or upper inner margin for the parent element

100. How to deal with the dependency of useEffect as a reference type?

1. Use 'use-deep-compare-effect': it can perform deep comparison, and the method of use is very simple, just import useDeepCompareEffect from 'use-deep-compare-effect' and replace the original useEffect with useDeepCompareEffect. 
2. You can also use the useRef hook to solve the above problems. The feature of useRef is to save data across rendering cycles. 
3. Use useRef to save the previous data. The dependency in useEffect is the reference type, which will be called every time obj changes. function, but there is an extra judgment in the execution function, prevObj is the value of obj in the last rendering, compare a key in prevObj with a key in obj this time, and do other operations after the conditions are met

101. Do you know the createPortal in react, and talk about its usage scenarios?

1. Portal, which renders child nodes to DOM nodes that exist outside the parent component.
2. ReactDOM.createPortal(child, container)
The first parameter (child) is any renderable React child element, such as an element, string or fragment. The second parameter (container) is a DOM element.
2. Portals are suitable for components that are out of flow, especially for components with position: absolute and position: fixed. Such as modal box, notification, warning, goTop, etc.

Version 2.0 (updated content)

1. Tell me about your understanding of Event Loop?

1. Event Loop is a mechanism in JavaScript for processing asynchronous events and callback functions. It is a loop in the JavaScript runtime environment, which continuously takes out tasks from the task queue and executes them until the task queue is empty. 2. The working principle of Event Loop: a. Execute synchronous code and put asynchronous operations into the task queue b. When the main thread task is idle, Event Loop will check whether there is a task in the task queue c. If there is a task, take out the task and Execute d. After completing the task, check the task queue again and repeat the operations of b and c. 3. Event Loop is a very important concept in JavaScript, which enables JavaScript to handle asynchronous operations and improves program performance and user experience.

2. Tell me about your understanding of BOM. What do you know about common BOM objects?

1. BOM refers to the browser object model, which provides objects that interact with the browser window independently of the content. 2. Its function is to interact with the browser, such as how to back, forward, refresh, and browser The window changes, the scroll bar scrolls, and some customer information is obtained, such as the browser brand version, screen resolution 3, window: The core object of the BOM is window, which represents an instance of the browser. In the browser, The window object has a dual role, which is an interface of the browser window and a global object. Therefore, all variables and functions declared in the global scope will program the properties and methods of the window object. 4. local: 5. navigator: main It is used to obtain the properties of the browser and distinguish the browser type. There are many attributes, and the compatibility is more complicated. 6. screen: it saves purely client capability information, that is, the information of the client display outside the browser window, such as pixel width and pixel height. 7. history: the object is mainly used for operation The history of the browser URL, which can be forwarded, backward, or redirected to the specified URL through parameters

3. What are the kernels of browsers, and what are the differences?

The common browser kernels are as follows:

  1. Trident kernel: It is a browser kernel developed by Microsoft, mainly used in Internet Explorer browser.

  2. Gecko kernel: It is the kernel of Mozilla Firefox browser and is also adopted by other browsers.

  3. WebKit kernel: It is a browser kernel developed by Apple, mainly used in Safari browser and Chrome browser.

  4. Blink kernel: It is a browser kernel developed by Google based on the WebKit kernel, mainly used in Chrome browser and Opera browser. 5. Differences: 1. The main reason is that the rendering engines are different, which leads to differences in browser performance, compatibility, security, etc. 2. The Trident kernel is relatively slow in processing CSS and JavaScript. 3. The Gecko kernel pays more attention to security and privacy protection. 4. The WebKit kernel is famous for its fast rendering speed and good compatibility. 5. The Blink kernel is better at performance and stability improvements.

4. Tell me about the difference between progressive enhancement and graceful degradation of browsers?

1. Both progressive enhancement and graceful degradation of browsers are designed to solve compatibility problems between different browsers or devices. 2. Progressive enhancement means that when designing and developing websites or applications, the realization of basic functions should be considered first. Then gradually add more advanced functions and interactive effects to adapt to the capabilities of different browsers and devices. 3. Progressive enhancement focuses more on forward compatibility, even on older browsers. 4. Graceful degradation It means that when designing and developing websites or applications, first consider the realization of advanced functions and interactive effects, and then gradually reduce the requirements to adapt to older browsers and devices that do not support these functions. Post-compatibility, which means better user experience on newer browsers

5. What are the solutions for website performance optimization?

1、尽量减少HTTP的请求次数:合并js、css等 2、 压缩文件:压缩CSS、JavaScript、HTML等文件,减少文件大小,提高网页加载速度。 3、 图片优化:使用适当的图片格式,压缩图片大小,减少图片数量,提高网页加载速度。 4、CDN加速:使用CDN(内容分发网络)加速网站访问速度,将网站内容分发到全球各地的服务器上,使用户可以从最近的服务器获取内容。 5、缓存优化:使用浏览器缓存和服务器缓存,减少重复请求,提高网站访问速度。 6、前端优化:减少HTTP请求,使用CSS Sprites、合并JavaScript文件等技术,减少页面加载时间。 7、数据库优化:优化数据库查询语句,使用索引,减少数据库查询时间,提高网站访问速度。 8、服务器优化:使用高性能服务器,优化服务器配置,提高网站访问速度。 9、去除冗余代码:去除无用的代码,减少页面大小,提高网站访问速度。 10、响应式设计:使用响应式设计,使网站可以适应不同的设备和屏幕大小,提高用户体验。

6、Link和@import之间有什么区别?

1、Link和@import都是用于引入外部资源的方法 2、不同: 1、加载顺序的不同:Link标签在加载页面的时候就会同时加载外部的资源,而@import在页面加载完毕之后才会加载外部资源 2、兼容性的不同:Link标签在所有浏览器中都被支持,而@import在一些旧的版本浏览器中可能不被支持 3、作用范围不同:Link标签可以用于引入各种类型的资源,包括CSS、JavaScript、图像等,而@import只能用于引入css文件 4、优先级不同:Link标签的优先级高于@import,因此如果同一个样式表这两种方法都使用的话,那么Link就会覆盖@import的样式

7、说说你对BFC的理解,触发条件有哪些?

1. BFC is a block-level formatting context, which refers to an independent rendering area, in which elements are laid out and rendered according to certain rules. 2. BFC features: 1. Internal elements are arranged one after another in the vertical direction to 
form 
    a Vertical flow 
    2. The BFC area will not overlap with floating elements 
    3. The BFC area will not overlap with the margin of external elements 
    4. The BFC area can contain floating elements 
    5. The BFC area can prevent elements from being covered by the border of the parent element 
3. Trigger Conditions: 
    1. The root element or the element containing the root element 
    2. The floating element float is not equal to none 
    3. The absolute positioning position is absolute or fixed 
    4. The display is inline-block, table-cell, table-caption, flex, inline-flex 
    5. Block-level elements whose overflow is not visible

8. What is the difference between null and undefined?

1. In js, both null and undefined mean that there is no value 2. Differences: 1. undefined means that a variable has been declared but not assigned a value, or the object property does not exist 2. null means that a variable has been assigned a value of null, or an object The attribute is assigned a value of null 3. In the conditional statement, both undefined and null will be converted to false, but in the comparison operator, the behavior is different. Undefined is false when compared with any value including itself, but null is only compared with undefined is true

9. What are the ways in which elements in css are separated from the document flow? What are the positioning methods and the differences?

1. There are several ways for elements in CSS to leave the document flow: 1. Float (float): Move the element out of the document flow so that it can be displayed side by side with other elements. 2. Absolute positioning (position: absolute): Moves the element out of the document flow and positions it relative to its nearest positioned ancestor element. 3. Fixed positioning (position: fixed): Move the element out of the document flow and position it relative to the browser window. 4. Flexible layout (display: flex): By setting the parent element as a flexible container, its child elements can be separated from the document flow and arranged according to certain rules. 5. Grid layout (display: grid): By setting the parent element as a grid container, its child elements can be separated from the document flow and arranged according to certain rules. 2. The positioning methods are as follows: 1. Relative positioning (position: relative): Positioning relative to the position of the element in the document flow will not affect the position of other elements. 2. Absolute positioning (position: absolute): Positioning is performed relative to the nearest positioned ancestor element, or relative to the body element of the document if there is no positioned ancestor element. 3. Fixed positioning (position: fixed): It is positioned relative to the browser window and will not move as the page scrolls.

3. Difference: The difference between relative positioning and absolute positioning is that relative positioning will not break away from the document flow, while absolute positioning will break away from the document flow. Fixed positioning is similar to absolute positioning, but it is positioned relative to the browser window and does not move as the page is scrolled.

10. What is the difference between synchronous and asynchronous?

1. Synchronous and asynchronous means that tasks are executed in different ways during task processing. 2. Synchronous tasks mean that tasks are executed sequentially. Each task must wait for the completion of the previous task before it can be executed. In synchronous execution, The execution of the task is blocked, that is to say, when the task is executed, it will wait until the task is completed before continuing to execute the next task. 3. Asynchronous execution means that the tasks are not executed in sequence, and each task can be executed independently. Wait for the previous task to complete. In the execution of an asynchronous task, the execution of the task is non-blocking, that is, the execution of the task will not wait for the completion of the task, but continue to execute the next task 4. The difference between synchronous and asynchronous lies in the way the task is executed. Sequential execution, while asynchronous execution is executed independently, without waiting for the completion of the previous task. In practice, asynchronous execution can usually improve the response speed and efficiency of the program

11. What is the difference between pseudo-classes and pseudo-elements? What are the new selectors in Css3?

The difference between pseudo-classes and pseudo-elements: 1. Pseudo-classes are used to describe some special states of elements, such as :hover, :active, :focus, etc., while pseudo-elements are used to create some elements that are not in the document tree, such as ::before , ::after, etc. 2. Pseudo-classes are represented by a single colon (:) in CSS2, and pseudo-elements are represented by double colons (::). 3. Pseudo-classes can be used for any element, while pseudo-elements can only be used for some specific elements. 4. Pseudo-classes can be used anywhere in the selector, while pseudo-elements can only be used in the last position of the selector. The new selectors in CSS3 include: 1. Attribute selectors: [attr=value], [attr~=value], [attr|=value], [attr^=value], [attr$=value], [attr *=value] 2. Pseudo-class selectors: :nth-child(), :nth-last-child(), :nth-of-type(), :nth-last-of-type(), :first- child, :last-child, :first-of-type, :last-of-type, :only-child, :only-of-type, :not() 3. Pseudo-element selectors: ::before, :: after, ::first-letter, ::first-line, ::selection 4. Combined selectors: AB, A > B, A + B, A ~ B

12. Tell me about the difference between Promise and async/await?

Promises and async/await are both ways of handling asynchronous operations, but there are some differences between them.

  1. Syntax: Promise is an asynchronous programming method based on callback functions, using .then() and .catch() methods to process the results of asynchronous operations. And async/await is an asynchronous programming method introduced by ES2017, using async and await keywords to process the results of asynchronous operations.

  2. Readability: Compared with Promise, async/await is easier to read and understand, and the code is more concise and clear.

  3. Error handling: In Promise, error handling requires the use of the .catch() method to catch errors. In async/await, try/catch statements can be used to catch errors.

  4. Chain call: Promise can call multiple asynchronous operations in a chain, while async/await can only proceed to the next asynchronous operation after one asynchronous operation is completed. In general, async/await is a more intuitive, readable, and easy-to-understand asynchronous programming method, but in some cases, Promise is also very useful.

13. Talk about the difference between rearrangement and redrawing? What are the trigger conditions?

Reflow and repaint are two important concepts when the browser renders the page. Reflow means that when the layout of elements on the page changes, the browser needs to recalculate the position and size of the elements and rearrange the layout of the page. Reflow will cause the page to be re-layouted and re-rendered, which is a relatively performance-intensive operation. Repainting (repaint) means that when the style of an element in the page changes, the browser needs to repaint the style of the element. Redrawing does not change the layout of the page, but only redraws the style of the element, so it is less expensive than reflowing. Conditions that trigger reflow include: 1. The initial rendering of the page 2. The size of the browser window changes 3. The position, size, and content of the element change 4. The style of the element changes 5. The conditions that trigger redrawing when the page scrolls include: 1 . The style of the element changes 2. The background color, border color, text color and other attributes of the element change 3. The transparency of the element changes 4. The text content of the element changes In general, rearrangement and redrawing will affect the page Therefore, it is necessary to avoid frequently triggering rearrangement and redrawing during the development process. Page performance can be optimized through reasonable layout design, using CSS3 animation instead of JavaScript animation, etc.

14. How does Javascript implement inheritance?

1、原型链继承:通过将子类的原型对象指向父类的实例对象来实现继承。 2、构造函数继承:指通过在子类构造函数中调用父类构造函数来实现继承。 3、组合继承:组合继承指的是将原型链和构造函数继承结合起来的一种继承方式,实现方式就是通过在子类构造函数中调用父类构造函数来继承父类的属性,并将子类的原型对象指向一个新的父类实例对象来继承的方法。 4、ES6中的class继承:通过使用extends关键字来继承父类,并使用super来调用父类的构造函数和方法。

15、说说什么是严格模式,限制都有哪些?

严格模式是 JavaScript 的一种执行模式,它强制执行一些限制,以帮助开发者编写更加健壮的代码。在严格模式下,一些不安全的行为会被禁止,一些错误也会被抛出。 严格模式下的限制包括: 1. 禁止使用未声明的变量。 2. 禁止删除变量、函数或函数参数。 3. 禁止使用 eval() 函数创建变量或函数。 4. 禁止使用 with 语句。 5. 禁止在函数内部使用 arguments.callee 和 arguments.caller。 6. 禁止对只读属性赋值。 7. 禁止扩展内置对象的原型。 8. 禁止在函数内部重复声明变量。 严格模式可以通过在代码的开头添加 "use strict"; 来启用。在严格模式下编写代码可以帮助开发者避免一些常见的 JavaScript 错误,并提高代码的可读性和可维护性。

16、如何快速的让一个打乱一个数组的顺序,比如 var arr = [1,2,3,4,5,6,7,8,9,10]?

  1. 从数组的最后一个元素开始,向前遍历数组。

  2. 随机生成一个 0 到当前遍历的索引值之间的整数。

  3. 将当前遍历的元素与随机生成的索引所对应的元素交换位置。

  4. 继续向前遍历数组,重复步骤 2 和 3,直到遍历到数组的第一个元素为止。

17、Vue的自定义指令钩子函数有哪些?你用自定义指令做过什么?

Vue's custom instruction hook functions include: bind, inserted, update, componentUpdated, unbind. 1. bind: It is called only once. It is called when the instruction is bound to the element for the first time. You can perform a one-time initialization setting here. 2. inserted: Called when the bound element is inserted into the parent node, but it may not be inserted into the DOM before its parent node. 3. update: Called when the template where the bound element is located is updated, regardless of whether the bound value changes. Unnecessary template updates can be ignored by comparing bound values ​​before and after the update. 4. componentUpdated: Called when the template where the bound element is located completes an update cycle. 5. unbind: called only once, when the instruction is unbound from the element. I once used a custom command to implement a function that clicks on the outer area to close the popup window. The specific implementation method is to bind a click event of a document in the bind hook function. When the click event is triggered, it is judged whether the clicked area is inside the pop-up window, and if not, the pop-up window is closed. Unbind the event in the unbind hook function.

18. Jump from page A to page B, cache component A, jump from component A to component C, cancel cache, how to achieve?

1. Keep-alive can pass the BeforeRouter(to, from, next) of the current page when to === "B" & from === "A" The parameter in the meta of keep-alive is true when to === "C ” & from ===”A” The parameter in the meta of keep-alive is false 2. Life cycle, get this.router.meta to modify the parameters in the meta of the page, and keep-alive will decide whether to activate the component according to the parameters in the meta cache

19. What are the responsive principles and differences between Vue2 and Vue3?

1. The responsive principle in Vue2 and Vue3 is based on Object.defineProperty. When the data changes, an update of the view is automatically triggered. However, Vue3 optimizes the principle of responsiveness, using Proxy proxy objects instead of Object.defineProperty, making the responsive system more efficient and flexible. 2. The responsive principle in Vue2 is that when instantiating a Vue object, it will recursively traverse each property in the data, convert each property into a getter and setter, and when the property is accessed or modified, it will trigger getter and setter methods, enabling responsive updates. 3. The responsive principle in Vue3 uses a Proxy proxy object, which can intercept object access and modification operations, thereby realizing responsive updates. The reactive system in Vue3 also supports the reactive function, which can convert an ordinary object into a reactive object, allowing developers to use the reactive system more flexibly. 4. In general, the responsive system in Vue3 is more efficient and flexible than Vue2, but there are some differences in use, which require developers to learn and adjust properly.

20. How does Vue implement permission management, and how to realize button-level permissions?

1. Divide all permissions into first-level permissions and second-level permissions according to the level, generate relative tree numbers, obtain the id of each permission, put each id in a list, and assign the foreign key to the role's permission 2. The button permission is that each button is bound to a processing method. When the logged-in user returns a role id that does not correspond to the button’s permission method, the button will be hidden.



the first week

21. The difference between Vue2 and Vue3 is at least 5 points?

  1. Performance optimization: Vue3 has carried out a lot of optimizations in terms of performance, including compiler optimization, responsive system optimization, virtual DOM optimization, etc., making the performance of Vue3 faster than Vue2.

  2. Composition API: Vue3 introduces Composition API, which is a new API style that can better organize and reuse component logic, making the code clearer and easier to maintain.

  3. TypeScript support: Vue3's support for TypeScript is more complete, which can better perform type checking and code hints, and improve the reliability and maintainability of the code.

  4. Better Tree-Shaking: Vue3 adopts a more modern ES module syntax, which can better support Tree-Shaking and reduce the packaging volume.

  5. Better adaptability: Vue3 has better adaptability to the web and mobile terminals, and can better support technologies such as PWA and SSR.

  6. Better error handling: Vue3 introduces an error handling mechanism that makes it easier for developers to locate and resolve errors.

22. The process of component communication in Vue3 [father to son, son to father]?

1. The process of component communication in vue3 is divided into two ways: parent-to-son and son-to-father. 
2. Father-to-son: 
    the parent component transmits data to the child component through props, and the child component receives data through props. The parent component can use the child component in the template, and pass the data to the child component through the v-bind instruction, and the child component can declare the received data type and default value 
in 
    props Send events to the parent component, the parent component listens to the events sent by the child component through the v-on command, and the child component can pass the $emit method to the parent component

23. What is the principle of Apply/call/bind?

1. Apply, call, and bind are all methods used in JavaScript to change the execution context of a function. 2. The functions of allpy and call are the same. They both change the execution context of the function, that is, change the this pointer inside the function. The difference between them lies in the way of passing parameters. apply receives an array as a parameter, and call receives multiple Parameter 3, the bind method is also used to change the execution context of the function, but it will not execute the function immediately, but return a new function, the this of this new function points to the bound object 4, in general, apply , call, and bind are all methods used to change the execution context of a function. The difference between them is the method of passing parameters and the return value. apply and call execute the function immediately, while bind returns a new function.

24. Tell me about your understanding of prototype and prototype chain?

1. Prototype is an important concept in JavaScript. It is an object through which other objects can inherit properties and methods. Every JavaScript object has a prototype object, which defines the properties and methods of that object. If a property or method cannot be found in the current object, the JavaScript engine will automatically search for the prototype object of the object until it is found. 2. The prototype chain is a chain structure composed of prototype objects, which is a way to implement inheritance in JavaScript. When an object needs to access a property or method of another object, the JavaScript engine looks up the prototype chain until it finds the property or method. Returns undefined if the property or method cannot be found in the entire prototype chain. 3. In JavaScript, each object has a proto attribute, which points to the prototype object of the object. When we access a property or method of an object, the JavaScript engine will first check whether the object itself has the property or method, and if not, it will search up the prototype chain until it is found. Returns undefined if the property or method cannot be found in the entire prototype chain. 4. In short, prototype and prototype chain are very important concepts in JavaScript, they can help us realize inheritance and sharing properties and methods between objects.

25. Tell me about your understanding of Generator in ES6?

1. The Generator in ES6 is a special function that can pause and save the current state during execution, and then resume execution when needed. The Generator function implements the function of suspending and resuming execution through the yield keyword. 2. The Generator function can be used for asynchronous programming. You can use the yield keyword to suspend the execution of the asynchronous operation, and wait for the asynchronous operation to complete before continuing. The Generator function can also be used to implement an iterator, which can return a value through the yield keyword, and then continue execution on the next call. 3. In addition, the Generator function can also accept parameters, which can be passed in when calling the Generator function, and then these parameters can be used inside the function. 4. In short, the Generator function is a very powerful tool that can be used to implement functions such as asynchronous programming and iterators, which can greatly simplify code writing and maintenance.

26. Tell me about the difference between the browser event loop and the nodeJs event loop?

There are several differences between the browser event loop and the Node.js event loop as follows: 1. The browser event loop is single-threaded, while the Node.js event loop is multi-threaded. 2. The tasks in the browser event loop are divided into macrotasks and microtasks, while the Node.js event loop only has macrotasks. 3. Microtasks in the browser event loop include Promise, MutationObserver, and process.nextTick, while there is no process.nextTick in the Node.js event loop, but there is setImmediate. 4. The macro tasks in the browser event loop include script, setTimeout, setInterval, I/O, UI rendering, etc., while the macro tasks in the Node.js event loop include I/O, timer, setImmediate, etc. 5. The task execution sequence in the browser event loop is to execute all microtasks first, and then execute a macro task, while the task execution sequence in the Node.js event loop is to execute all I/O and timer tasks first, and then Execute the setImmediate task. In general, both the browser event loop and the Node.js event loop are based on an event-driven model, but their implementation methods and task execution sequences are different.

27. Tell me about your understanding of browser caching mechanism?

The browser cache mechanism means that when the browser accesses a web page, it will cache some static resources (such as pictures, CSS, JS, etc.) locally, so that the next time you visit the same web page, it can be directly read from the local cache, thereby improving the performance of the web page. Loading speed and user experience. 1. There are two types of browser caching mechanisms: strong caching and negotiation caching. 2. Strong caching means that when the browser requests the resource for the first time, it will store the expiration time (Expires) or the maximum cache time (Cache-Control) of the resource locally. The next time it requests it, it will first determine whether the local cache has expired. If it has not expired, the resource will be read directly from the local cache without sending a request to the server. 3. Negotiation caching means that when the browser requests a resource for the first time, it will store the resource identifier (ETag or Last-Modified) locally, and will send a request to the server for the next request, and the server will judge the resource according to the resource identifier Whether there is an update, if there is no update, a 304 status code is returned, and the browser directly reads the resource from the local cache. 4. The browser caching mechanism can effectively reduce network requests, improve webpage loading speed and user experience, but it may also cause resources to not be updated in time. It is necessary to use the caching mechanism reasonably during development to avoid problems.

28. Tell me about your understanding of the browser kernel?

The browser kernel can be divided into two parts: rendering engine and JS engine 1. Rendering engine: responsible for obtaining the content of the web page (HTML, XML, images, etc.), organizing information (adding css, etc.), and calculating the display mode of the web page , which is then output to a monitor or printer. Different browser kernels will have different grammatical interpretations of web pages, so the rendering effect will also be different. Therefore, choosing a suitable browser kernel is very important for browser performance and user experience.

29. Tell me about your understanding of Vue's responsive principle?

Vue's responsive principle is realized through data hijacking. When a Vue instance is created, Vue will monitor all its data, and when the data changes, Vue will automatically update the view. The specific implementation method is as follows: 1. Vue will traverse the data object during instantiation and convert each property into a getter/setter, so that Vue can monitor when the property is accessed or modified. 2. When the data changes, Vue will monitor the change through the setter method and notify all components that depend on the data to update. 3. Vue uses a Dep class to manage all dependencies. Each data corresponds to a Dep instance. When the data changes, Dep will notify all Watcher instances that depend on the data to update. 4. The Watcher instance is an important concept in Vue. It will be created when the component is rendered, and will be notified to update when the data changes. Each Watcher instance is associated with a Dep instance, and when data changes, Dep will notify all associated Watcher instances to update. In general, Vue's responsive principle is realized through data hijacking, Dep class and Watcher instance, which can automatically monitor data changes and update views, which greatly simplifies the development process.

30. What is the difference between Methods watch computed?

1. Both Methods and watch are used in Vue.js to monitor data changes. 2. Methods is an option in Vue.js, used to define methods in components. It can accept parameters, perform some operations, and return results. When the data in the component changes, if some data needs to be recalculated, it needs to be recalculated in the method and return the result. 3. Watch is a special option in Vue.js, which is used to monitor data changes and perform some operations. It can monitor the change of one or more data, and execute the specified callback function when the data changes. When you need to perform some asynchronous operations or complex calculations when data changes, you need to use watch. 4. The difference is: 1. Methods are used to define methods in components, which can accept parameters, perform some operations, and return results. And watch is used to monitor data changes and perform some operations, it cannot accept parameters, nor can it return results. 2. Methods are usually used for simple operations such as calculating attributes or processing events, while watches are usually used to handle complex asynchronous operations or calculations, or when multiple data changes need to be monitored.

  1. Computed is a computed attribute in Vue.js, it can also be called in the template, but its implementation is different from Methods. Computed is based on dependency caching, that is, it will only be recalculated when the dependent data changes. If the dependent data has not changed, Computed will directly return the results in the cache, thereby improving performance.

31. Tell me about your understanding of Virtual DOM?

Virtual DOM is a technology used to optimize the performance of web applications. It is a lightweight JavaScript object that simulates the hierarchy and properties of the real DOM, and can operate in memory instead of manipulating the real DOM directly. When the Virtual DOM changes, it will compare it with the real DOM, and only update the parts that need to be updated, thereby reducing the number of DOM operations and improving the performance of the application. The advantages of Virtual DOM include: 1. Improve application performance: Since Virtual DOM only updates the parts that need to be updated, it reduces the number of DOM operations and improves application performance. 2. Simplify application development: Since Virtual DOM can operate in memory, application development and testing can be performed more easily. 3. Improve application maintainability: Since Virtual DOM makes application development and testing easier, it can improve application maintainability. In conclusion, Virtual DOM is a very useful technology that can help us improve the performance and maintainability of web applications.

32. Tell me about your understanding and function of nextTick?

1. nextTick is an asynchronous method in Vue.js. Its function is to execute the specified callback function after the next DOM update cycle ends. The main function of nextTick is to perform some operations immediately after Vue.js updates the DOM, such as obtaining the size or position of the DOM element immediately after updating the data. 2. The implementation principle of nextTick is to use the event loop mechanism of JavaScript. When Vue.js updates the DOM, it puts all DOM update operations into a queue and waits for the next event loop to execute. The nextTick method is to put the specified callback function into this queue and wait for the execution of the next event cycle. 3. NextTick has a wide range of usage scenarios. For example, using the $nextTick method in Vue.js can perform some operations immediately after the DOM is updated, such as obtaining the size or position of the DOM element. In addition, using the nextTick method in Vue.js can also solve some asynchronous data update problems, such as obtaining the updated data immediately after the data is updated. 4. In short, nextTick is a very important asynchronous method in Vue.js, which can help us perform some operations immediately after the DOM is updated, thereby improving the performance and user experience of the application.

33. Tell me about your understanding of webpack?

Webpack is a modern JavaScript application packaging tool. It can package multiple JavaScript files, CSS files, images and other static resources into one or more bundle files for easy loading and use in browsers.

The main functions of Webpack include: 1. Modular management: Webpack supports CommonJS, AMD, ES6 and other modular specifications, and can package multiple modules into one file, reducing the number of HTTP requests and improving page loading speed. 2. Code conversion: Webpack can convert high-level languages ​​such as ES6, TypeScript, and CoffeeScript into JavaScript codes that browsers can recognize. 3. Code splitting: Webpack can split the application into multiple chunks to achieve on-demand loading and improve page loading speed. 4. Resource management: Webpack can process static resources such as CSS, images, and fonts, package them into one or more files, and perform operations such as compression and optimization on them. 5. Plug-in system: Webpack provides a rich plug-in system, which can realize various automatic operations, such as code compression, file copy, HTML generation, etc. In short, Webpack is a very powerful tool that can help developers better manage and package JavaScript applications, improve development efficiency and user experience.

34. Talk about the difference between GET and POST?

1. GET and POST are two commonly used request methods in the HTTP protocol 2. Differences: 1. The GET request method is used to obtain resources, while the POST request method is used to submit data. 2. The data of the GET request method will be appended to the URL, separated by a question mark "?", and the parameters will be separated by an "&" symbol, while the data of the POST request method will be included in the request body. 3. The data transmission volume of the GET request method is small, generally no more than 2KB, while the data transmission volume of the POST request method is relatively large, and data of any size can be transmitted. 4. The data of the GET request method can be cached, can be bookmarked, and can be recorded in the browser history, while the data of the POST request method will not be cached, nor can it be bookmarked, nor will it be recorded in the browser history record record. 5. The security of the GET request method is low, because the data will be exposed in the URL, which is easy to be intercepted and tampered with, while the security of the POST request method is high, because the data will not be exposed in the URL, only in the request body data can be intercepted and tampered with.

35. Talk about the difference between HTTP and HTTPS. What is the encryption principle of HTTPS?

1. HTTP is the hypertext transfer protocol, which is a protocol used to transmit data. It is transmitted in clear text, and the data is easy to be eavesdropped and tampered with. 2. HTTPS adds the SSL/TLS protocol on the basis of HTTP, and ensures data security through encryption and authentication technologies. HTTPS uses encrypted transmission, and encryption is performed during data transmission to ensure data confidentiality and integrity. 3. Specifically, HTTPS will perform an SSL/TLS handshake before transmitting data, establish a secure channel, and then transmit data. The SSL/TLS protocol uses two encryption methods: asymmetric encryption and symmetric encryption. Asymmetric encryption is used to establish a secure channel, and symmetric encryption is used to encrypt data transmission. 4. During the SSL/TLS handshake process, the server will send its own public key to the client. The client uses the public key to encrypt a random number, and then sends it to the server. The server uses its own private key to decrypt the random number, and then uses This random number generates a symmetric key for encrypted data transmission. 5. Compared with HTTP, HTTPS has higher security and confidentiality, and is suitable for websites that need to protect user privacy and sensitive information, such as banks and e-commerce websites.

36. Why does TCP need three handshakes?

The TCP protocol requires a three-way handshake to establish a connection, mainly to ensure that both parties to the communication can send and receive data normally. The specific reasons are as follows: 1. The first handshake: the client sends a connection request segment to the server, and the server will reply with a confirmation segment after receiving the request, indicating that the client's request has been received. 2. The second handshake: After receiving the client's request, the server will send a confirmation message segment to the client, indicating that it has received the client's request and is ready to communicate with the client. 3. The third handshake: After receiving the confirmation segment from the server, the client will send a confirmation segment to the server, indicating that it has received the confirmation from the server and is ready to communicate with the server. 4. Through the three-way handshake, it can ensure that both parties in the communication can send and receive data normally, and can avoid connection failure or data transmission error due to network delay or packet loss. At the same time, the three-way handshake can also prevent security problems caused by malicious attacks or misinformation in the network.

37. Tell me about the principle of Proxy proxy?

A proxy is a web application that acts as an intermediary between a client and a server. Its principle is to establish a proxy server between the client and the server. The client sends a request to the proxy server, and the proxy server forwards the request to the server. After the server responds, the result is returned to the proxy server, and the proxy server returns the result to the proxy server. client.

The workflow of Proxy is as follows: 1. The client sends a request to the proxy server. 2. The proxy server receives the request and forwards the request to the server. 3. The server responds to the request and returns the result to the proxy server. 4. The proxy server receives the result and returns the result to the client.

The role of the Proxy agent mainly includes the following aspects: 1. Improve access speed: The proxy server can cache the request results, and when the same request is made next time, it will directly return the cached results, thereby improving the access speed. 2. Access control: The proxy server can filter and control the client's request, such as restricting access to certain websites or restricting the access of certain clients. 3. Hiding client information: The proxy server can hide the real IP address of the client, thereby protecting the privacy of the client. 4. Load balancing: The proxy server can distribute requests to multiple servers to achieve load balancing and improve server performance and reliability. In short, Proxy proxy is a very useful network application, which can improve access speed, protect privacy, achieve load balancing and other functions.

38. Talk about the understanding of memory leaks? What are the situations of memory leaks?

Memory leak refers to the phenomenon that the requested memory space is not released correctly during the running of the program, resulting in the continuous reduction of available memory in the system, which eventually leads to a program crash or system crash. Memory leaks are usually due to some wrong memory management operations in the program, such as not releasing dynamically allocated memory, repeatedly releasing memory, using already released memory, and so on.

There are several types of memory leaks: 1. The memory is not released after being dynamically allocated: The program uses the dynamically allocated memory during operation, but does not release it after use, resulting in a memory leak. 2. Circular reference: When two or more objects refer to each other, if the reference relationship between them is not handled correctly, memory leaks will result. 3. The file is not closed: When the program uses the file, if the file is not closed properly, it will cause a memory leak. 4. The cache is not cleared: When the program uses the cache, if the cache is not cleaned up correctly, it will cause a memory leak. 5. Program error: There are some wrong memory management operations in the program, such as using already released memory, repeatedly releasing memory, etc., which will lead to memory leaks.

Memory leaks will slow down the running speed of the program, and even cause the program to crash or the system to crash. Therefore, in program development, it is necessary to pay attention to memory management and release unused memory space in time.



The third week

39. Tell me about the difference between arrow functions and ordinary functions?

The main differences between arrow functions and ordinary functions are as follows: 1. An arrow function does not have its own this, and its this is inherited from the outer scope. The this of ordinary functions is dynamically bound when the function is called, and its value depends on how the function is called. 2. Arrow functions cannot use the arguments object, nor can they be called using the new keyword. Ordinary functions can use the arguments object, or they can be called using the new keyword. 3. The arrow function has no prototype attribute, so it cannot be used as a constructor. Ordinary functions can be used as constructors to create new object instances. 4. The syntax of the arrow function is more concise, and the return keyword and curly braces in the function body can be omitted. Ordinary functions must use the return keyword to return a value, and the function body must be enclosed in curly braces. 5. In general, arrow functions are suitable for simple functions, which can make the code more concise and easy to read. Ordinary functions are more flexible and can handle various scenarios.

40. How to solve the slow loading speed of the first screen of SPA?

  1. Code optimization: Check whether there are redundant, repeated or unnecessary codes in the code, reduce the amount of code as much as possible, and optimize the code structure and algorithm to improve the page loading speed.

  2. Image optimization: If the image is too large, you can use an image compression tool to compress it to reduce the size of the image, thereby improving the page loading speed.

  3. Lazy loading: For resources such as pictures and videos on the page, lazy loading technology can be used to load only when the user scrolls to the corresponding position, thereby reducing the loading time of the first screen.

  4. CDN Acceleration: Use CDN (Content Delivery Network) acceleration service to distribute static resources on servers around the world, thereby improving page loading speed.

  5. Cache optimization: Use browser caching technology to cache static resources in the page locally, and read them directly from the cache on the next visit, thereby reducing server requests and improving page loading speed.

  6. Server optimization: In the case of slow server response, you can consider using a higher-configured server, or use load balancing technology to distribute requests to multiple servers, thereby improving page loading speed.

41. Talk about the common Loader in webpack? What problem did it solve?

  1. babel-loader: convert ES6/ES7/JSX and other syntax into ES5 syntax, which solves the browser compatibility problem.

  2. css-loader: Parse CSS files and process dependencies, such as @import and url(), so that CSS files can be packaged into JS files.

  3. style-loader: Inject CSS code into the <style> tag in the HTML page to make the style take effect.

  4. file-loader: Copy the file to the output directory and return the file path, which solves the file path problem.

  5. url-loader: Similar to file-loader, but it can convert files smaller than the specified size into base64 encoding, reducing HTTP requests and improving page loading speed.

  6. image-loader: Load and compress image files, solving the problem of slow image loading.

  7. json-loader: Load JSON files, solving the problem of manual parsing when using JSON files.

  8. xml-loader: Loads XML files, solving the problem of manual parsing when using XML files. These Loaders solve different problems, such as browser compatibility, file path, style injection, image loading speed, etc., so that Webpack can process various types of files and package them into one or more JS files, which improves the application Program performance and maintainability.

42. What is your understanding of SPA single page, what are its advantages and disadvantages? How to realize SPA application?

SPA single-page application means that the entire application has only one page, and all page content is realized by asynchronously loading data and dynamically updating the page. SPA applications are usually implemented using front-end frameworks (such as React, Angular, Vue, etc.). Advantages: 1. Good user experience: SPA applications can realize page switching without refreshing, and the user experience is smoother. 2. Separation of front-end and back-end: SPA applications can separate the front-end and back-end. The front-end only needs to focus on page display and interaction logic, and the back-end only needs to provide API interfaces. 3. Improve performance: SPA applications can reduce page refreshes, reduce server load, and improve performance. Disadvantages: 1. Slow loading of the first screen: SPA applications need to load all front-end codes and data, and the loading time of the first screen is longer. 2. Unfriendly to SEO: Since the SPA application has only one page, it is difficult for search engines to crawl the content of the page, which is unfriendly to SEO. 3. Browser compatibility issues: SPA applications need to use some new features of HTML5, and have high requirements for browser compatibility. Ways to implement SPA applications: 1. Use front-end frameworks: Use front-end frameworks such as React, Angular, and Vue to quickly implement SPA applications. 2. Use routing libraries: Use routing libraries such as React Router and Vue Router to achieve page refresh switching. 3. Use AJAX technology: AJAX technology can be used to load data asynchronously and dynamically update page content.

43. What is the difference between components and plugins in Vue?

The difference between components and plug-ins in Vue is as follows: 1. Components are the basic concepts in Vue, and are reusable code blocks in Vue applications, used to encapsulate UI components or business logic. Components can be used multiple times in a Vue application, can receive data passed by the parent component, and can also send data to the parent component. 2. Plug-ins are extended functions in Vue, which are some optional functional modules used to enhance the functions of Vue applications. Plugins can add global methods or properties, global directives or filters, and Vue instance methods or mixins. 3. Components and plugins are used differently. Components need to be registered in the Vue application before they can be used. Components can be registered through the Vue.component() method or the Vue.extend() method. The plug-in can be installed through the Vue.use() method, or it can be used directly in the Vue instance. 4. Components and plug-ins have different scopes. Components are mainly used to encapsulate UI components or business logic, and the scope of action is usually local and only used within a certain component. Plug-ins are mainly used to enhance the functions of Vue applications, and the scope of action is usually global and can be used in the entire Vue application.

44. What are the communication methods between Vue components?

The communication methods between Vue components are as follows: 1. Parent-child component communication: the parent component passes data to the child component through props, and the child component passes data to the parent component through events. 2. Sibling component communication: Data can be passed to sibling components through a common parent component as an intermediary. 3. Cross-level component communication: You can use provide/inject to pass data downward, or use $parent/$root to find parent components upward. 4. Non-parent-child component communication: You can use Event Bus (Event Bus) or Vuex to achieve communication between non-parent-child components. The event bus is an empty Vue instance that can be used to fire and listen to events. Vuex is a state management library, which can centrally manage data and realize shared state between components.

45. Do you know the diff algorithm of vue? Tell me?

Vue's diff algorithm is an efficient virtual DOM comparison algorithm, which is used to calculate the difference between the two virtual DOM trees before and after, and apply the difference to the real DOM to minimize DOM operations. Vue's diff algorithm adopts a double-ended comparison strategy, that is, the comparison starts from the head and tail of the old and new virtual DOM trees at the same time, so as to reduce the number of comparisons as much as possible. Specifically, Vue's diff algorithm is divided into the following steps: 1. First compare the root nodes of the old and new virtual DOM trees. If the node types are different, replace the entire node directly; if the node types are the same, go to the next step of comparison. 2. Compare the attributes and events of the nodes, and update the attributes and events of the nodes if there is any change. 3. Compare the child nodes of the node. If the number of child nodes is different, directly replace the child nodes of the entire node; if the number of child nodes is the same, go to the next step of comparison. 4. For child nodes at the same position, perform the above steps recursively until all child nodes are compared. 5. For the redundant nodes in the new virtual DOM tree, directly add them to the real DOM; for the redundant nodes in the old virtual DOM tree, directly delete them from the real DOM. Through the above steps, Vue's diff algorithm can efficiently calculate the difference between the two virtual DOM trees before and after, and apply the difference to the real DOM to minimize DOM operations.

46. ​​Briefly talk about Virtual Dom?

1. Virtual Dom is a technology that abstracts the state of the page into a virtual DOM tree. It is one of the core technologies of front-end frameworks such as React and Vue. 2. The working principle of Virtual Dom is that when the page state changes, the framework will first convert the new state into a new virtual DOM tree, and then compare the new virtual DOM tree with the old virtual DOM tree to find Find out the difference between the two, and finally only update the part that needs to be updated, thus avoiding unnecessary DOM operations and improving the performance of the page. 3. The advantage of using Virtual Dom is that it allows developers to focus on the state management of the page without caring about the specific implementation details of the page. At the same time, since Virtual Dom can reduce DOM operations, it can improve the performance and responsiveness of the page.

47. What is the difference between the Composition Api used by Vue3.0 and the Options Api used by Vue2.x?

The Composition Api used by Vue3.0 is different from the Options Api used by Vue2.x in the following ways: 1. The way to organize code is different: Composition Api is function-based, while Options Api is object-based. 2. Stronger reusability: Composition Api can better realize logic reuse, and can encapsulate logic code into functions to facilitate reuse in multiple components. 3. Better type inference: Composition Api can better support TypeScript because it uses more type inference. 4. Better code readability: Composition Api can better organize code, make code clearer and easier to read, and reduce confusion and duplication in Options Api. 5. Better responsiveness: reactive and ref in Composition Api can better handle responsive data, making the code more concise and easy to understand. In short, Composition Api has great advantages in code organization, reusability, type inference, code readability, and responsiveness, which can better help developers build high-quality Vue applications.

48. Talk about the setState execution mechanism in React?

In React, setState is the method used to update the state of the component. When the setState method is called, React will merge the new state object into the current state object and re-render the component. The specific execution mechanism is as follows: 1. When calling the setState method, React will add the new state object to an update queue. 2. If the setState method is called multiple times in the same event loop, React will combine these updates into one update and only perform one update operation. 3. When the setState method is called in the component lifecycle function and event handler, React will add the update to the queue and perform the update operation after the current event loop ends. 4. When the setState method is called in an asynchronous operation, React will add the update to the queue and perform the update operation in the next event loop. 5. Before the update operation is executed, React will optimize the update queue to remove duplicate updates and invalid updates to improve performance. In summary, React's setState method is an asynchronous operation that adds the update to the queue and performs the update operation at the appropriate time. When using the setState method, care should be taken to avoid infinite loops and unnecessary updates to improve component performance.

49. Talk about the understanding of class components and function components in React? What's the difference?

1. Both class components and function components are a way to define components. 2. Class components are defined using the class syntax in ES6, must inherit the React.Component class, and must implement the render method to return the jsx of the component; class components can use state and lifecycle methods to manage the state and behavior of the component 3. Functional components are defined using functions. They only need to return JSX. Functional components cannot use state and lifecycle methods, but you can use React Hook to manage the state and behavior of components. Differences: 1. Grammar: class components use class syntax, function components use function syntax. 2. State management: Class components can use state to manage the state of components, while function components need to use React Hooks to manage state. 3. Life cycle: Class components have life cycle methods, such as componentDidMount() and componentWillUnmount(), etc., while function components do not have life cycle methods. 4. Performance: Functional components are usually more lightweight than class components because they do not need to inherit the React.Component class and implement the render() method. However, if you need to manage state and behavior, functional components may need to use React Hooks, which may affect performance.

50. Tell me about your understanding of React Hooks? What problem did it solve?

React Hooks is a new feature introduced in React 16.8, which allows us to use state and other React features without writing a class. React Hooks solve the following problems: 1. It is difficult to reuse state logic between components. React Hooks provide a way to share state logic called custom Hooks. 2. Complex components become difficult to understand. React Hooks can split components into smaller functions, each focusing on a specific functionality. 3. The relationship between lifecycle methods and state logic in the Class component is not intuitive. React Hooks can separate lifecycle methods and state logic, making the code easier to understand and maintain. 4. The this binding problem in the Class component. Functional components in React Hooks do not have this binding issues, making the code more concise and easier to maintain. In summary, React Hooks provide a simpler and more intuitive way to write React components, making the code easier to understand and maintain.

51. How do UseMemo and useCallback improve performance, and what are the application scenarios?

Both UseMemo and useCallback can be used to optimize the performance of React components. UseMemo can cache calculation results to avoid repeated calculations, thereby improving the rendering performance of components. Its application scenarios include: 1. Values ​​with high calculation cost, such as obtaining data from API and performing complex calculations. 2. Optimize the rendering of subcomponents to avoid unnecessary rendering. 3. Avoid creating new objects or arrays every time you render. UseCallback can cache functions to avoid creating new functions every time they are rendered, thereby improving the rendering performance of components. Its application scenarios include: 1. Avoid unnecessary rendering of subcomponents when passing functions as props to subcomponents. 2. When using useEffect, avoid repeated execution of useEffect due to function reference changes. 3. When using useMemo, avoid double calculation of useMemo due to function reference changes.

52. What is the implementation principle of Vue-router?

Vue-router is a routing management plugin officially provided by Vue.js. Its implementation principle mainly includes the following aspects: 1. Based on the component development idea of ​​Vue.js, the routing rules are abstracted into components, and the page jump and refresh are realized through the nesting and switching of components. 2. Use the HTML5 History API to change the URL address of the browser through the pushState and replaceState methods, so as to realize the jump and refresh of the front-end route. 3. Use the responsive data binding mechanism of Vue.js to store the routing information in the data attribute of the Vue instance, and monitor the routing changes through the watch, so as to realize the dynamic update and response of the routing. 4. Use the lifecycle hook functions of Vue.js, such as beforeRouteEnter, beforeRouteUpdate, beforeRouteLeave, etc., to implement route interception and control, thereby realizing route authority management and page dynamic loading. In short, the implementation principle of Vue-router is based on the component development idea of ​​Vue.js and the responsive data binding mechanism, using HTML5 History API and Vue.js life cycle hook function to realize the front-end routing jump, refresh, interception and control.

53. How to package components and use them between different projects?

To package components for use in different projects, follow these steps: 1. Create a separate component library project that contains all components to be packaged. 2. In the component library project, create a separate folder for each component, and contain all the code and styles of the component in it. 3. In each component folder, create a index.jsfile that will export all necessary content for the component, such as component classes, styles, and other dependencies. 4. In the component library project, use a packaging tool such as webpack to package all components into a single JavaScript file. 5. Publish the component library project to npm or other package manager so other projects can use it. 6. In other projects, use npm installthe command to install the component library. 7. In the file that needs to use the components, import the required components and use them.

54. What is the difference between vue, react, and angular?

Vue, React, Angular are all modern JavaScript frameworks for building single page applications (SPA) and dynamic web applications. The differences between them are as follows: 1. Vue.js is a lightweight framework, easy to learn and use, suitable for small projects. React.js is a library that provides more flexibility and customizability, suitable for large projects. Angular is a complete framework that provides many features and tools, suitable for large enterprise-level projects. 2. The template syntax of Vue.js is simpler and more intuitive, easy to understand and maintain. React.js uses JSX syntax, which requires more learning and understanding. Angular uses HTML and TypeScript, which requires more learning and mastery. 3. The performance of Vue.js is better because it uses virtual DOM and asynchronous rendering. React.js also uses virtual DOM, but it needs to be manually optimized for performance. Angular has relatively poor performance because it uses two-way data binding and a lot of dependency injection. 4. Both Vue.js and React.js are open source, with an active community and a large number of plugins and components available. Angular is also open source, but has a relatively small community due to its complexity and learning curve.

55. Tell me about your understanding of Redux? How it works?

Redux is a JavaScript state management library that helps us manage and update state in our applications. The core concept of Redux is the store, which is a JavaScript object that contains the state of the entire application. Redux uses actions and reducers to update the state in the store. When an event in the application occurs, we can create an action object, which describes the type of event and related data. Then, we pass this action object to a reducer function, which will update the state in the store according to the type of action. The reducer function receives the current state and action object as parameters and returns a new state object. The working principle of Redux can be summarized as the following steps: 1. Create a store object, which contains the state of the entire application. 2. Define action objects, which describe events in the application. 3. Create a reducer function that updates the state in the store based on the type of action. 4. Pass the action object to the reducer function, which will return a new state object. 5. Update the state in the store to match the new state object. 6. Subscribe to changes in the store in the application to update the UI when the state changes.

The advantage of Redux is that it can help us better organize and manage the state of the application, making the application more predictable and maintainable. At the same time, Redux can also be integrated with frameworks and libraries such as React, making it easier for us to use it to manage the state of the application.



The first weekly exam 2205A

56. Tell me about your understanding of the box model?

The box model means that in a web page, each element is regarded as a rectangular box, which consists of four borders, inner margins, outer margins, and content areas. This model can help us better understand and control the layout and style of elements in web pages. Specifically, the box model includes the following parts: 1. Content area (content): the actual content of the element, such as text, pictures, etc. 2. Padding: The blank area between the content area and the border can be controlled by setting the padding property. 3. Border: The lines surrounding the content area and padding can be controlled by setting the border property. 4. Margin: The blank space between the border and adjacent elements can be controlled by setting the margin attribute. In practical applications, we can control the size, position, border style, background color, etc. of elements by setting various properties of the box model. At the same time, the box model is also the basis of CSS layout. By using the box model reasonably, we can achieve various complex layout effects.

57. What are the selectors of CSS? Priority? Which can be inherited?

CSS selectors are as follows: 1. Element selector (element selector): select elements by element name, such as p, div, a, etc. 2. Class selector (class selector): Select elements by class name, starting with ".", such as .class. 3. ID selector (ID selector): Select elements by ID, starting with "#", such as #id. 4. Attribute selector (attribute selector): Select elements through the attributes of the elements, such as [type="text"]. 5. Pseudo-class selector (pseudo-class selector): select elements by their state, such as :hover, :active, :visited, etc. 6. Pseudo-element selector (pseudo-element selector): used to select a certain part of the element, such as ::before, ::after, etc. The priority of CSS selectors from high to low is: 1. !important 2. Inline style (style attribute) 3. ID selector 4. Class selector, attribute selector, pseudo-class selector 5. Element selector, The CSS properties that pseudo-element selectors can inherit are as follows: 1. Font family properties (font-family, font-size, font-weight, etc.) 2. Text family properties (text-align, text-indent, text-decoration etc.) 3. Color attributes (color, background-color, etc.) 4. List attributes (list-style-type, list-style-image, etc.) 5. Table layout attributes (border-collapse, border-spacing, etc.) 6. Others Attributes (visibility, cursor, etc.)

58. What are the methods of centering elements horizontally and vertically? What if the element has a variable width and height?

There are several ways to center elements horizontally and vertically: 1. Use flex layout: set the parent element to display: flex;, and set justify-content: center; and align-items: center; to achieve horizontal and vertical centering. 2. Use absolute positioning: set the parent element to relative positioning, set the child element to absolute positioning, and set top: 50%; and left: 50%;, then use transform: translate(-50%, -50%); Horizontal and vertical centering can be achieved. 3. Use table layout: set the parent element to display: table;, set the child element to display: table-cell;, and set vertical-align: middle; and text-align: center; to achieve horizontal and vertical centering.

If the element has a variable width and height, you can use the following methods: 1. Use flex layout: set the parent element to display: flex;, and set justify-content: center; and align-items: center;, and set the child element to flex: 1 ; You can achieve horizontal and vertical centering. 2. Use absolute positioning: set the parent element to relative positioning, set the child element to absolute positioning, and set top: 50%; and left: 50%;, then use transform: translate(-50%, -50%); and max-width: 100%; and max-height: 100%; can achieve horizontal and vertical centering 3. Use table layout: set the parent element to display: table;, set the child element to display: table-cell;, and Set vertical-align: middle; and text-align: center;, then use max-width: 100%; and max-height: 100%; to achieve horizontal and vertical centering.

59. How to understand reflow and redraw? Under what circumstances will it be triggered?

Reflow and repaint are two important concepts when the browser renders the page. Reflow means that when the position and size of elements on the page change, the browser needs to recalculate the position and size of the element, and then re-layout the entire page. This process is reflow. Reflow will cause the page to re-render, so it will be more performance-intensive. Redrawing means that when the style attributes of elements on the page change, the browser only needs to redraw the styles of these elements without recalculating the position and size of the elements. This process is called redrawing. Redrawing is less expensive than reflowing.

Reflow and redraw are triggered in the following scenarios: 1. When the page is loaded for the first time, the browser needs to reflow and redraw. 2. When the position, size, content and other attributes of elements in the page change, reflow and redrawing will be triggered. 3. When the style attribute of an element in the page changes, a redraw will be triggered. 4. When the size of the browser window changes, reflow and redraw will be triggered. 5. When the page scrolls, a redraw is triggered.

Therefore, when writing pages, you should try to avoid frequent reflow and redrawing, and you can optimize page performance in the following ways: 1. Use CSS3's transform and opacity properties to achieve animation effects, and avoid using properties such as position and float. 2. Use position: absolute or fixed to position elements, and avoid using attributes such as margin and padding. 3. To avoid frequently modifying the style attributes of DOM elements, multiple modification operations can be combined into one operation. 4. Use techniques such as virtual lists to optimize the rendering of large amounts of data.

60. What is responsive design? What are the basic principles of responsive design? How to do?

Responsive design is a web design method that can make the website present the best user experience on different devices (such as desktop computer, tablet computer, mobile phone, etc.). The basic principle of responsive design is to automatically adjust the layout, font size, picture size and other elements of the webpage to adapt to the screens of different devices by using technologies such as CSS media query and elastic grid layout, according to the screen size and resolution of different devices size and resolution.

To do a good job in responsive design, you need to follow the following steps: 1. Design elastic grid layout: Use relative units (such as percentage, em, etc.) to define the size and position of web page elements to adapt to the screen sizes of different devices. 2. Use CSS media queries: According to the screen size and resolution of different devices, use CSS media queries to adjust the layout, font size, picture size and other elements of the web page. 3. Optimize image size: Use proper image format and compression techniques to reduce image size to improve web page loading speed. 4. Testing and optimization: Test the responsive design effect of the webpage on different devices, and optimize according to the test results to improve user experience.

61. Tell me about your understanding of the box model?

1. The box model means that in a web page, each element is regarded as a rectangular box, which includes four parts: content, inner margin, border and outer margin. Among them, the content area is the actual display content of the element area, padding is the distance between the content area and the border, which is the line around the content and padding, and margin is the distance between the border and adjacent elements.

2. The size of the box model is determined by the height and width attributes of the element, but the actual size also needs to add the values ​​of inner margin, border and outer margin. In css, the calculation method of the box model can be controlled by the box-sizing attribute . There are two values: content-box and border-box. content-box indicates that the size of the box model includes only the content area, while border-box indicates that the size of the box model includes the content area, inner margins, and borders, but does not include outer margins.

3. The box model is very important in web page layout. Various layout effects can be achieved by setting the attributes of the element's width, height, inner margin, border and outer margin. At the same time, the box model can also control the position and hierarchical relationship of elements through the positioning properties of CSS.

62. How to center a box horizontally and vertically? What are the methods?

  1. Use flex layout, set the parent container to display:flex, and then use justify-content:center and align-items:center to achieve horizontal and vertical centering

  2. Using absolute positioning, set the left and top properties of the box to 50%, and then use transform:translate(-50%,-50%) to achieve horizontal and vertical centering.

  3. Use table layout, set the parent container to display:table, then set the box to display:table-cell, use vertical-align:middle and text-align:center to achieve horizontal and vertical centering.

63. Tell me about the data types in JavaScript and how to store them?

JavaScript has seven data types, namely:

  1. Basic data types: Number, String, Boolean, Null, Undefined, Symbol (new in ES6).

  2. Reference data type: Object.

  3. The value of the basic data type is stored in the stack memory, while the value of the reference data type is stored in the heap memory, and the pointer to the actual data in the heap memory is stored in the stack memory.

  4. When we create a variable of a basic data type, a space will be allocated in the stack memory, and the value will be stored in this space;

  5. When we create a variable of a reference data type, a space is allocated in the stack memory, which stores a pointer to the actual data in the heap memory, and the actual data is stored in the heap memory.

64. How to understand responsiveness? What are the ways to achieve it? What's the difference?

1. Responsive website is a kind of network page design layout. Page design and development should respond and adjust according to user behavior and device environment (system platform, screen size, screen orientation, etc.)

2. Media query: use @media to define different styles according to different screen sizes

3. Percentage: Relative to the measurement unit of the containing block, set the percentage to the property to adapt to different screens

4. vw/vh: Viewport unit, which can be adapted according to the browser window size

5. rem: refers to the unit relative to the font size of the root element, rem is only a relative unit

65. What are the common methods of Css performance optimization, and how to achieve them?

1. Avoid excessive constraints

2. Avoid descendant selectors

3. Use compact syntax

4. Avoid unnecessary namespaces

5. Avoid unnecessary repetition

6. It is best to use semantic names to define

7. Avoid !important, you can choose other selectors

8. Streamline the rules as much as possible, and merge different types of repeated rules

66. What are the methods to judge the data type? What's the difference?

1、 typeof :

a. Can judge the data type, it returns a string representing the data type, the returned result can only include number, Boolean, string, function, object, undefined

b. You can use typeof to determine whether a variable exists

c. The problem with the typeof operator is that it returns object no matter what type the referenced object is

2, instanceof method:

Generally used to detect the reference data type, the expression is: A instanceof B, to determine whether A is an instance of B, if A is an instance of B, return true, otherwise return false, the data type is determined by the construction type

3, constructor method:

constructor is an attribute on the prototype object, pointing to the constructor,

4. Invincible and omnipotent method: jquery.type()

If the object is undefined or null, return "undefined" or "null" accordingly.

If the object has an internal [[Class]] that is the same as a browser's built-in object [[Class]], we return the corresponding [[Class]] name

67. What is the difference between Bind, Call and Apply? How to implement a bind method?

1. , call, applyfunction bindis to change the context when the function is executed, in short, it is to change thisthe pointing of the function when it is running

2. applyIt accepts two parameters. The first parameter is thisthe pointer, and the second parameter is the parameter accepted by the function, which is passed in in the form of an array. thisAfter changing the pointer, the original function will be executed immediately, and this method only temporarily changes thisthe pointer once

3. callThe first parameter of the method is also thisthe pointer, and a parameter list is passed in later. The original function will be executed immediately after applychanging thisthe pointer, and this method only temporarily changes thisthe pointer once. When the first parameter is null, undefinedtime, the default points to window(in the browser)

4. The bind method is very similar to call. The first parameter is also thisthe pointer, and a parameter list is also passed in later (but this parameter list can be passed in multiple times). thisAfter changing the pointer, it will not be executed immediately, but will return a permanent change thisthe function pointed to

5. Difference:

  • All three can change thisthe object pointed to by the function

  • The first parameter of the three is thisthe object to be pointed to. If there is no such parameter or the parameter is undefinedor null, it will point to the global by defaultwindow

  • All three can pass parameters, but applyit is an array, callbut a parameter list, applyand callthe sum is a one-time incoming parameter, but bindit can be divided into multiple incoming

  • bindis to return the function after binding this, apply, callis to execute immediately

  • modify thispoint

  • Pass parameters dynamically

// Method 1: Only pass function parameters in bind 
fn.bind(obj,1,2)() 
​//
Method 2: Pass function parameters in bind, and also pass parameters in the return function 
fn.bind(obj, 1)(2)
  • compatible newkeyword

The overall implementation code is as follows:

Function.prototype.myBind = function (context) { 
    // Determine whether the calling object is a function 
    if (typeof this !== "function") { 
        throw new TypeError("Error"); 
    } 
​//
    Obtain parameters 
    const args = [ ...arguments].slice(1), 
          fn = this; 
​return
    function Fn() { 
​//
        Depending on the calling method, pass in different binding values 
        ​​return fn.apply(this instanceof Fn ? new fn(... arguments) : context, args.concat(...arguments)); 
    } 
}

68. How to understand closure? What is the application scenario of closure?

1. A function is bundled with references to its surrounding state (lexical environment, lexical environment) (or the function is surrounded by references), such a combination is a closure (closure), that is, a closure allows you to Access to the scope of its outer function in an inner function

2. Application scenarios:

  • create private variables,

  • Extend the lifetime of variables

  • cache data

  • Implement the callback function

69. Briefly talk about what is an event agent?

1. Event delegation (Event Delegation), also known as event delegation. is a common technique for binding events commonly used in JavaScript. As the name suggests, "event proxy" is to delegate the response events (click, keydown...) that originally need to be bound to the child elements to the parent element, and let the parent element take on the role of event monitoring. The principle of event proxy is the event bubbling of DOM elements.

70. What are anti-shake and throttling? What's the difference? How to achieve?

1. Anti-shake means that after the event is triggered, nthe callback is executed after a delay of seconds. If nthe event is triggered again within this second, the timing will be restarted.

2. Throttling means that the event is executed after n seconds. If it is triggered repeatedly within n seconds, the timing will be re-timed, which can reduce the trigger frequency of the event within a period of time.

3. Difference:

Same point:

  • can be setTimeoutachieved by using

  • The purpose is to reduce the frequency of callback execution. Save computing resources.

    difference:

  • Function anti-shake, after a period of continuous operation, handle callback, use clearTimeoutand setTimeoutimplement. Function throttling, in a continuous operation, only executed once per period of time, used in high-frequency events to improve performance

  • Function anti-shake focuses on events that are triggered continuously for a certain period of time and is only executed once at the end, while function throttling is only executed once in a period of time

For example, the time frequency is set to 500ms, and within 2 seconds, the function is frequently triggered, throttling, and executed every 500ms. Anti-shake, no matter how many times the method is called, it will only be executed once after 2s

4. Application scenarios:

In the continuous event of anti-shake, only one callback needs to be triggered in the following scenarios:

  • Search box Search input. Only the user needs to enter the last time before sending the request

  • Mobile phone number, email verification input detection

  • window size resize. Just calculate the window size after the window resizing is done. Prevent re-rendering.

Scenarios where throttling executes a callback at intervals include:

  • Scroll to load, load more or scroll to the bottom to listen

  • Search box, search association function

71. Tell me about your understanding of the scope chain?

1. Find the required variable in the current scope, but 该作用域没有this variable, then this variable is 自由变量. If you find and search in 自己作用域找不到this variable , it will be terminated until you access the window object. The layer-by-layer relationship is去父级作用域查依次向上级作用域作用域链。

2. The role of the scope chain is to ensure the orderly access to all variables and functions that the execution environment has access to. Through the scope chain, you can access the variables and functions of the outer environment. The scope chain is essentially a list of pointers to variable objects. A variable object is an object that contains all variables and functions in the execution environment. The front end of the scope chain is always the variable object of the current execution context.

72. Talk about the understanding of prototype and prototype chain?

1. Prototype:

  • When JS declares a constructor (a function used to instantiate an object), it will create a corresponding object in memory, which is the prototype of the original function. The constructor has a prototype attribute by default, and the value of prototype points to the prototype of the function. At the same time, there is also a constructor attribute in the prototype, and the value of the constructor points to the function object.

  • The object instantiated through the constructor does not have the prototype attribute, it has a proto attribute by default, and the value of proto points to the prototype of the constructor. The properties added or modified on the prototype object can be shared on all instantiated objects.

  • Function: data sharing, saving memory space; realizing inheritance

2. Prototype chain :

  • When accessing a property in an instantiated object, it will first search inside the object (its own property). If it cannot find it, it will search for it in the prototype pointed to by its proto . If it still cannot find it, it will continue to search for it in the prototype. Search in the superior prototype pointed to by proto until it finds or Object.prototype.proto (the value is null), this chain process is the prototype chain.

  • Function: Find the attribute method of the object

73. What are the life cycle and meaning of vue?

1. The life cycle of vue refers to a series of processes from the beginning of creation, initialization of data, compilation of templates, hanging on DOM and rendering, update rendering, and uninstallation

2. beforeCreate(): Before creation, after a new vue instance, there are only some default life cycle hooks and default events, and other things have not been created yet. When this life cycle is executed, the data in data and methods have not been initialized. The data in data and the methods in methods cannot be used at this stage

3. created(): created, data and methods have been initialized and can be called

4. BeforeMount(): Before mounting, the template has been compiled in memory, but it has not been mounted to the page. At this time, the page is still old

5. mounted(): mounted, the Vue instance has been initialized. At this point, the component leaves the creation phase and enters the running phase. If we want to manipulate the DOM nodes on the page through plug-ins, we can do it at this stage at the earliest

6. beforeupdate(): Before the update, the data displayed on the page is still old, the data in data is updated, and the page has not been synchronized with the latest data

7. updated(): update, the data displayed on the page and the data in data have been kept in sync, and they are all up-to-date

8. beforeDestory(): Before destruction, the Vue instance enters the destruction stage from the running stage. At this time, all data and methods, instructions, filters... are available. haven't really been destroyed yet

9. Destoryed(): Destroyed, the Vue instance enters the destruction stage from the running stage. At this time, all data and methods, instructions, filters... are available. haven't really been destroyed yet

74. What are the hook functions of vue custom instructions?

  • bind: Called only once, when the directive is bound to the element for the first time. One-time initialization settings can be performed here.

  • inserted: Called when the bound element is inserted into the parent node (only the parent node is guaranteed to exist, but not necessarily inserted into the document).

  • update: Called when the VNode of the component is updated, but it may happen before the update of its child VNode. The value of the directive may or may not have changed. But you can ignore unnecessary template updates by comparing the values ​​before and after the update (see below for detailed hook function parameters).

  • componentUpdated: Called after the VNode of the component where the command is located and its child VNodes are all updated.

  • unbind: Called only once, when the instruction is unbound from the element.

75. What are the JavaScript local storage? Differences and usage scenarios?

1. javaScriptWe mainly describe the following four methods of local caching:

  • cookie

  • sessionStorage

  • localStorage

  • indexedDB

2. The main differences between cookie, sessionStorage, localStorageand are as follows:

  • Storage size: cookiethe data size cannot exceed 4k, sessionStorageand localStoragealthough there is also a storage size limit, it is cookiemuch larger than that, and can reach 5M or greater

  • Effective time: localStoragestore persistent data, the data will not be lost after the browser is closed unless the data is actively deleted; the sessionStoragedata will be automatically deleted after the current browser window is closed; it will be valid until cookiethe set cookieexpiration time, even if the window or browser is closed

  • 数据与服务器之间的交互方式,cookie的数据会自动的传递到服务器,服务器端也可以写cookie到客户端; sessionStoragelocalStorage不会自动把数据发给服务器,仅在本地保存

3、针对不对场景的使用选择:

  • 标记用户与跟踪用户行为的情况,推荐使用cookie

  • 适合长期保存在本地的数据(令牌),推荐使用localStorage

  • 敏感账号一次性登录,推荐使用sessionStorage

  • 存储大量数据的情况、在线文档(富文本编辑器)保存编辑历史的情况,推荐使用indexedDB



月考111

76、说说你对递归的理解?封装一个方法用递归实现树形结构封装?

1、递归是一种算法或者函数的实现方式,他通过调用自身来解决问题。在递归的过程中,每次调用都会将问题分解为更小的子问题,直到问题被分解为足够小的部分,可以直接求解

2、递归通常可以用来解决具有递归结构的问题,比如像树形结构和图形结构等。

77、Link和@import有什么区别?

1、Link和@import都是用于引入外部资源的方法,但是也有所区别

区别:

1、加载时间:Link标签在页面加载时同时进行加载;@import是在页面加载完毕后再进行加载。

2、兼容性:Link标签是HTML标签,兼容性比较好;@import是css语法,不兼容旧版本的浏览器。

3、作用范围:Link标签可以引入各种类型的文件,比如CSS、JS、图片等;而@import只能引入CSS文件

4、权重:Link标签引入的CSS文件的权重高于@import引入的CSS文件,因此在样式进行冲突的时候,Link标签引入的样式会覆盖@import引入的样式

78、什么是FOUC?如何避免?

1、FOUC是文档样式暂时失效,指的是在网页加载时,由于CSS文件未能及时加载,导致页面出现短暂的样式化内容的现象。

如何避免:

1、将CSS文件放在HTML文档的头部,这样可以确保CSS文件在页面加载时首先被加载

2、使用内联CSS样式,将CSS样式直接嵌入HTML文档中,这样可以避免CSS问价加载时的延迟。

3. Using CSS preprocessors, such as Sass and Less, can compile CSS files into a single CSS file, thereby reducing the amount of HTTP requests

4. Use browser cache to cache CSS locally, which can reduce page loading time

5. Use JavaScript to detect whether the CSS file has been loaded when the page is loaded. If the loading is not completed, the rendering of the page can be delayed until the CSS file is loaded.

79. Tell me about your understanding of precompilers?

1. A precompiler is a program that processes the source code before compiling it. It can perform some preprocessing operations, such as macro replacement, conditional compilation, header file inclusion, etc. The precompiler is a part of the compiler, which can be executed automatically during compilation or by command

2. The main function of the precompiler is to replace the macro definition in the source code with the actual code, and insert the content in the header file into the source code. This reduces code duplication and improves code readability and maintainability.

3. The precompiler can also perform conditional compilation, and generate different codes according to different conditional compilation options. In this way, different codes can be generated according to different requirements, and the flexibility and portability of the code can be improved.

80. What is the function of shouldcomponentUpdate?

1. shouldComponentUpdate is one of the React lifecycle methods used to control whether the component needs to be re-rendered. Its function is to determine whether the props and state of the component have changed before the component is re-rendered. If there is no change, it returns false, otherwise it returns true, telling React that the component needs to be re-rendered.

2. Using shouldComponentUpdate can improve the performance of React applications because it can avoid unnecessary re-rendering. When the props or state of the component changes, React will re-render the component. If the props or state of the component has not changed, then re-rendering is unnecessary. At this time, shouldComponentUpdate can be used to avoid unnecessary re-rendering.

81. Outline transaction processing logic in React?

The transaction processing logic in React means that in the life cycle of a React component, React will automatically create a transaction object to manage the update process of the component. The transaction object contains a series of lifecycle hook functions to perform specific operations during component updates.

82. What is the division of React components into business components and technical components?

1. React components can be divided into business components and technical components according to their functions and uses.

2. Business components refer to business-related components, such as login boxes, shopping carts, product lists, etc. These components are usually functional and can be shared by multiple pages or applications. Business components are usually composed of multiple technical components, such as forms, buttons, lists, and so on.

3. Technical components refer to components related to technology, such as forms, buttons, lists, etc. These components usually have common functions and can be shared by multiple business components. Technical components are typically composed of HTML, CSS, and JavaScript code that can be interacted with through props and state properties.

83. Which periodic function is React performance optimization?

React performance optimization is performed in the shouldComponentUpdate lifecycle function. This function is called before the component is updated, and can return false to prevent the component from re-rendering, thereby improving the performance of the application. In this function, you can decide whether to re-render the component by comparing props and state before and after.

84. Talk about the understanding and application scenarios of the Fiber architecture?

1. The Fiber architecture is a lightweight concurrency model based on coroutines, which can achieve high concurrent processing capabilities in a single thread.

2. The core idea of ​​the Fiber architecture is to decompose a long-term task into multiple small tasks, and then switch between these small tasks to achieve concurrent processing.

The application scenarios of Fiber architecture mainly include the following aspects:

1. Highly concurrent network applications: Fiber architecture can handle a large number of network requests in a single thread, thereby improving the concurrent processing capabilities of applications. 
2. High-performance database access: Fiber architecture can process multiple database requests in a single thread, thereby improving the performance of database access. 
3. Large-scale data processing: Fiber architecture can decompose large-scale data processing tasks into multiple small tasks, thereby improving the efficiency of data processing. 
4. Real-time data processing: Fiber architecture can realize real-time data processing, such as real-time monitoring, real-time log processing, etc.

85. React performance optimization solution?

  1. Use PureComponent or shouldComponentUpdate: PureComponent is a performance-optimized component provided by React. It will automatically perform a shallow comparison. If props and state have not changed, the component will not be re-rendered. If you are using a common Component, you can manually implement the shouldComponentUpdate method to perform custom comparison logic.

  2. Use React.memo: React.memo is a high-level component provided by React. It can cache the rendering result of the component. If the props have not changed, it will directly return the cached result without re-rendering the component.

  3. Avoid performing complex calculations and operations in the render method: the render method will be called every time the component is updated. If complex calculations and operations are performed in it, it will affect the performance of the component. These calculations and operations can be placed in the component's lifecycle method, or cached using memoization technology.

  4. Use React.lazy and Suspense: React.lazy is a lazy loading component provided by React, which can delay the loading of components until they need to be used. Suspense is a component provided by React, which can display a loading state when the component is loaded, and wait for the component to be loaded before displaying the component.

  5. Performance testing with shouldComponentUpdate and React.memo: You can use React's performance testing tool to test, find out which components need to be optimized, and then use shouldComponentUpdate or React.memo to optimize.

  6. Use React's Profiler tool for performance analysis: React provides a Profiler tool that can help developers analyze the rendering performance of components and find out which components need to be optimized.

86. Briefly describe the process of flux and css rendering?

Flux is an architectural pattern for building scalable web applications. Its core idea is one-way data flow, that is, data can only flow from one place to another, which can avoid data confusion and inconsistency.

The process of CSS rendering is to combine HTML documents and CSS style sheets to generate visual Web pages. The specific process is as follows:

1. The browser parses the HTML document and builds a DOM tree. 
1. The browser parses the CSS style sheet and builds a CSSOM tree. 
1. Combine the DOM tree and CSSOM tree to generate a rendering tree. 
1. According to the node information in the rendering tree, calculate the position and size of each node. 
1. Draw the nodes in the rendering tree to the screen to generate the final web page.

87. What is the difference between DOM0, DOM2, and DOM3 event processing?

DOM0, DOM2, and DOM3 refer to different versions of JavaScript DOM (Document Object Model) event processing specifications.

1. DOM0 event processing: In DOM0 event processing, the event handler is directly assigned to the attribute of the DOM element

2. DOM2 event handling: The DOM2 event handling specification introduces the addEventListener() and removeEventListener() methods, which allow multiple event handlers to be added to the same element.

3. DOM3 event handling: The DOM3 event handling specification introduces more event types and more event handler options.

88. How to judge that the page scrolls to the bottom, and how to judge whether the elements in the page enter the visualization area?

Judging that the page scrolls to the bottom can be done in the following ways:

  1. Get the scroll height of the page scrollTop, the visible height of the page clientHeight and the total height of the page scrollHeight.

  2. Determine whether scrollTop + clientHeight is equal to scrollHeight. If they are equal, it means that the page has scrolled to the bottom.

Judging whether elements in the page enter the visual area can be done in the following ways:

1. Obtain the position information of the element, including the offsetTop, offsetLeft, offsetWidth and offsetHeight of the element.

  1. Get the page scroll height scrollTop and page visible height clientHeight.

  2. Determine whether the position information of the element is between scrollTop and scrollTop + clientHeight, if it is, it means that the element has entered the visualization area.

89. Tell me about the difference between the browser Event Loop and the Event Loop in nodejs?

1. The main difference between the browser Event Loop and the Event Loop in nodejs lies in their implementation and operating environment.

2. The browser Event Loop is implemented based on a single-threaded JavaScript engine, which is responsible for handling JavaScript code execution and event processing.

3. The Event Loop in the browser mainly includes two types of task queues: macro tasks and micro tasks. Macro tasks include setTimeout, setInterval, DOM events, etc., while micro tasks include Promise, MutationObserver, etc. In each event loop, all microtasks are executed first, then a macrotask is executed, and then all microtasks are executed, and so on.

4. The Event Loop in nodejs is implemented based on multi-threaded C++, which is responsible for the execution of JavaScript code and the processing of I/O operations.

5. The Event Loop in nodejs mainly includes six stages: timers, pending callbacks, idle, prepare, poll and check. In each stage, Event Loop will execute the corresponding task queue until all tasks are executed.

90. Tell me about the underlying implementation principle of vue-router?

1. The underlying implementation principle of Vue-router is mainly based on the responsive system of Vue.js and the hash mode or history mode of routing.

2. In Vue.js, each component has a responsive state object. When the state changes, Vue.js will automatically update the view. Vue-router uses this feature to store routing information in a responsive state object. When the routing changes, Vue.js will automatically update the view.

3. In hash mode, Vue-router listens to the hashchange event of the browser. When the hash changes, Vue-router will update the routing status object according to the new hash value and trigger the view update.

4. In the history mode, Vue-router uses the HTML5 history API to change the URL of the browser through the pushState and replaceState methods, update the routing state object at the same time, and trigger the view update.

5. In order to prevent the user from manually modifying the URL, resulting in inconsistency between the routing state object and the view, Vue-router also uses the popstate event to monitor the back and forward operations of the browser, so as to update the routing state object and view in time.

6. In addition, Vue-router also provides routing guards, dynamic routing, nested routing and other functions. The realization of these functions is also based on the characteristics of the responsive system and routing mode of Vue.js.

91. Tell me about the realization principle of vuex? How are the commit and dispatch methods implemented?

1. Vuex is a state management library. Its implementation principle is based on the responsive system and one-way data flow mode of Vue.js.

2. Vuex stores the state of the application in a central repository called store. Components can access and modify the state in the store through getters and mutations, and actions can be used for asynchronous operations.

4. The commit method is a method for submitting a mutation, which receives two parameters: the name of the mutation and payload (optional). When the commit method is called, Vuex will look for the corresponding mutation in the store and execute it, thereby modifying the state in the store.

5. The dispatch method is used to trigger the action, which receives two parameters: the name of the action and the payload (optional). When the dispatch method is called, Vuex will look up the corresponding action in the store and execute it, thus triggering an asynchronous operation or some other side effects.

92. There are three components A, B, and C. A component jumps to B component cache, and A component jumps to C component without caching. How to achieve it?

1. You can use tags in routing configuration <keep-alive>to implement component caching.

2. In the routing configuration, wrap the component that needs to be cached in <keep-alive>a tag, and set includethe property to the name of the component that needs to be cached

3. In the component, use activatedlife deactivatedcycle hooks to determine whether caching is required. If caching is required, set it in activatedthe hook , set it in the hook$route.meta.keepAlivetruedeactivatedfalse

4. When jumping, judge whether caching is required according to the name of the component that needs to be cached. $route.meta.keepAliveIf caching is required, it is set to when jumping true, otherwise it is set tofalse



The second week of the sixth grade

93. Understanding of MVVM?

1. MVVM is a software architecture pattern that divides the application into three parts: model Model, view View, and view model ModelView. Among them, the model represents the data and business logic of the application, the view represents the user interface, and the view model is the middleware that connects the model and the view.

2. In MVVM, the view model is responsible for converting the data in the model into a format that the view can use, and converting the user operations in the view into a mode that the model can understand. The view model is also responsible for handling the communication between the view and the model. For example, like data binding, command binding, etc.

3. What are the advantages of MVVM?

1. Separation of concerns: Separate the data and business logic of the application from the user interface, making the code clearer and easier to understand.

2. Testability: Since the communication between the view model and the view and model is realized through data binding and command binding, it is easier to unit test the view model.

3. Maintainability: Since MVVM divides the application into three parts, it is easier to maintain and expand the application.

94. Please explain in detail your understanding of the vue life cycle?

The vue life cycle refers to the entire process of a vue instance from creation to destruction. The vue life cycle is divided into eight stages:

1. beforeCreate: Called before the instance is created. At this time, the data and methods of the instance have not been initialized, and attributes such as data, computed, and methods cannot be accessed.

2. created: Called after the instance is created. At this time, the data and methods of the instance have been initialized, but the DOM has not been rendered, and the DOM elements cannot be accessed.

3. beforeMount: Called before the DOM is mounted. At this time, the template has been compiled, but it has not been mounted on the page.

4. mounted: Called after the DOM mount is complete. At this time, the instance has been mounted on the page and DOM elements can be accessed.

5. beforeUpdate: Called before the data is updated. At this time, the data has been updated, but the DOM has not been re-rendered.

6. updated: Called after the data update is completed. At this time, the data has been updated and the DOM has been re-rendered.

7. beforeDestroy: Called before the instance is destroyed. At this time, the instance has not been destroyed, and some cleaning work can be performed.

8. destroyed: Called after the instance is destroyed. At this time, the instance has been destroyed, and the data and methods of the instance cannot be accessed.

95. What are the data transfer methods between vue components?

There are several ways to transfer data between Vue components:

  1. Parent-child components pass data: the parent component passes data to the child component through props, and the child component passes data to the parent component through $emit trigger event.

  2. Brother components pass data: data can be passed to sibling components through a common parent component as an intermediary.

  3. Use Vuex for data management: Vuex is Vue's state management library, which can store data in a global store, and each component can obtain and modify data through getters and mutations.

  4. Use the event bus for data transfer: You can use the Vue instance as the event bus to transfer data between components through the $on and $emit methods.

  5. Use provide and inject for data transfer: the parent component provides data to the child component through provide, and the child component injects data through inject.

  6. Use $refs for data transfer: You can get the instance of the subcomponent through $refs, so as to directly access the data and methods of the subcomponent.

96. Routing implementation of vue: principles of hash mode and history mode?

There are mainly two modes for routing implementation of UE: hash mode and history mode.

  1. Hash mode In hash mode, the content behind the # symbol in the URL is called a hash value, which will not be sent to the server, but processed on the client. When the hash value in the URL changes, the browser will trigger the hashchange event, and we can switch routes by listening to this event.

  2. For example, when we visit Example Domain , the browser will use the content after # as the hash value, that is, /home. When we click on the link on the page to switch to another route, we actually modify the hash value in the URL instead of sending a new request.

  3. History mode In history mode, the # symbol is no longer needed in the URL, but the normal URL path is used directly.

  4. When we visit http://example.com/home , the browser will send a request to the server, and the server will return the corresponding page content. When we click on the link on the page to switch to another route, we actually use the history API of HTML5 to modify the history of the browser through the pushState or replaceState method, and also modify the URL path.

97. What are the hook functions of vue routing?

The hook functions of Vue routing include:

  1. beforeEach(to, from, next): Executed before routing jumps, which can be used for global routing interception and permission control.

  2. afterEach(to, from): Executed after the route jumps, it can be used to perform operations such as page statistics and log records.

  3. beforeRouteEnter(to, from, next): Executed before entering the route, it can be used for asynchronous data acquisition and page initialization and other operations.

  4. beforeRouteUpdate(to, from, next): Executed when the current route is updated, and can be used to update components and synchronize data.

  5. beforeRouteLeave(to, from, next): Executed before leaving the current route, which can be used to save data and confirm pages.

98. What is the difference between v-if and v-show?

Both v-if and v-show are used to control the display and hiding of elements

1. v-if decides whether to render the element according to the value of the expression. If the value of the expression is false, the element will not be rendered to the page. If the value of the expression is true, the element will be rendered to the page middle.

2. v-if has a high switching performance overhead when switching, because it will re-render the element and its subcomponents every time it switches. v-show also determines whether the element is displayed based on the value of the expression

3. But the difference is that v-show only controls the value of the CSS property display of the element. If the value of the expression is false, the display property of the element is set to none, and the element still exists in the DOM. If the value of the expression If true, the element's display property is set to its original value, and the element still exists in the DOM.

4. v-show has no additional performance overhead when switching, because the element always exists in the DOM, and only controls its display and hiding.

99. What is the difference between $route and $router?

Both $route and $router are routing-related objects in Vue.js, but their functions and usage are different.

  1. $route is the routing information object in Vue.js, which contains some information about the current routing, such as routing path, parameters, query parameters, etc.

  2. The $route object can be accessed through this.$route in the component.

  3. $router is a routing instance object in Vue.js, which is responsible for managing routing jumps and navigation.

  4. The $router object can be accessed through this.$router in the component. Through the $router object, we can perform operations such as routing jumps and navigation.

100. How to make CSS only work in the current component?

  1. CSS modularization Using CSS modularization, CSS files can be separated from component files. Each component has its own CSS file, which can avoid CSS style conflicts. In React, CSS Modules library can be used to achieve CSS modularization.

  2. The steps to use CSS Modules are as follows: 1. Introduce the CSS file in the component file, and change the name of the CSS file to "filename.module.css". 2. When using a CSS class name in a component, you need to use "styles.class name" to refer to it.

  3. Using styles in components

  4. To use the less file, you only need to ensure that the class names of the outermost containers are not the same

101. <keep-alive></keep-alive>What is the function of the function?

  1. <keep-alive></keep-alive>It is a built-in component in Vue.js, and its function is to cache component instances to avoid repeated rendering and destruction.

  2. When a component is wrapped in <keep-alive></keep-alive>a tag, it is not destroyed but cached until it is used again.

  3. This improves the performance of your application because the component does not need to be re-rendered and initialized every time.

  4. When in use <keep-alive></keep-alive>, you can control which components need to be cached and which don't through settings includeand properties.exclude

102. Steps to use plugins in vue?

The steps to use plugins in Vue are as follows:

  1. Install plug-ins: Use package management tools such as npm or yarn to install the required plug-ins.

  2. Import plug-ins: Introduce plug-ins in the entry file (such as main.js) of the Vue project.

  3. Registering plugins: Register plugins using the Vue.use() method.

  4. Using plugins: Use the functionality provided by plugins in Vue components.

103. Please list three common life cycle hook functions in vue?

  1. created: It is called immediately after the instance is created, and operations such as data initialization and method definition can be performed at this stage.

  2. mounted: Called immediately after the instance is mounted on the DOM element, DOM operations and asynchronous requests can be performed at this stage.

  3. updated: When the data changes, the component will be re-rendered, and the updated hook function will be called at this time, and operations such as DOM operations and data updates can be performed at this stage.

104. What is Vue SSR?

  1. Vue SSR refers to the process of rendering Vue components into HTML strings on the server side, and then sending them to the browser side for display.

  2. advantage

    1. Better SEO: Traditional client-side rendering is not SEO friendly since search engine crawlers cannot execute JavaScript. And SSR can generate a complete HTML page on the server side, which is conducive to crawling and indexing by search engines.

    2. Faster first-screen loading speed: Traditional client-side rendering needs to download JavaScript files before rendering, which will result in slower first-screen loading speeds. However, SSR can generate a complete HTML page on the server side, reducing the rendering time on the client side, thereby improving the loading speed of the first screen.

    3. Better user experience: Since SSR can generate a complete HTML page on the server side, users can see the page content faster, reducing waiting time and improving user experience

105. What are the advantages of Proxy over definedProperty?

1. More flexible: Proxy can proxy the entire object, instead of only proxying a certain property of the object like defined Property, which makes the proxy more flexible and can handle more scenarios

2. More powerful: proxy can intercept more operations, such as function calls, constructors, etc., while defined Property can only intercept the read and write operations of object properties

3. More intuitive: the API of proxy is more intuitive, easy to understand and use, while the API of defined Property is more complicated, requiring a deeper understanding of the internal mechanism of the object

4. More secure: Proxy can prevent some common security vulnerabilities, such as object properties being tampered with, object properties being deleted, etc., but defined Property cannot completely solve these problems

5. More efficient: The performance of proxy is better than that of defined Property, because proxy can be optimized in the underlying implementation, while the implementation of defined Property is more complicated and its performance is relatively poor

106. What is vuex? how to use? Which functional scenarios use it?

  1. Vuex is a state management library specially designed for vuejs. It can centrally manage the state of all components in the vue application. The core concepts of vuex include state, mutation, getters, actions, modules

  2. state: store the state data of the application, which can be accessed through this.$store.state.

    1. mutations: used to modify the data in the state, only synchronous operations can be performed, and can be called through the this.$store.commit() method.

    2. actions: used to handle asynchronous operations, which can be called by this.$store.dispatch() method.

    3. getters: used to derive some state from the state, which can be accessed through this.$store.getters.

    4. modules: Divide the state of the application into multiple modules, each with its own state, mutations, actions, and getters

    To use Vuex, you need to install it in the Vue application first, which can be imported through npm or CDN. Then create a store object in the Vue application, pass in configuration items such as state, mutations, actions, getters, and modules, and finally inject the store object into the Vue instance in the Vue instance.

    Scenarios for using Vuex include: - There are multiple components in the application that need to share state data. - There is complex state logic in the application, which requires centralized management. - There are a large number of asynchronous operations in the application, which need to be managed uniformly.

107. Vue2.x responsive principle?

  1. The responsive principle of vue2.x is realized through data hijacking and publish-subscribe mode

  2. Data hijacking: Vue2.x implements data hijacking through the Object.defineProperty() method, that is, when data is accessed or modified, corresponding operations can be triggered. In Vue2.x, each component instance has a corresponding Watcher instance. When the data in the component changes, the Watcher instance will notify the component to re-render.

  3. Publish-subscribe mode: Vue2.x uses the publish-subscribe mode to implement data responsiveness. In Vue2.x, each component instance has a corresponding Dep instance, which is used to store the Watcher instance. When the data in the component changes, the Dep instance will notify all Watcher instances to update.

  4. The specific implementation process is as follows:

    1. In Vue2.x, data hijacking is implemented through the Object.defineProperty() method, that is, when data is accessed or modified, corresponding operations can be triggered.

    2. When a component instance is created, all data in the component will be traversed, a corresponding Dep instance will be created for each data, and all Watcher instances of the data will be stored in the Dep instance.

    3. When the data in the component changes, the setter method of the corresponding data will be triggered, and the setter method will notify the Dep instance corresponding to the data to update.

    4. The Dep instance will traverse all Watcher instances stored in it and notify them to update. 5. After the Watcher instance receives the update notification, it will trigger the re-rendering of the component.

108 What is the difference between ES5, ES6 and ES2015?

  1. ES5 is the abbreviation of ECMAScript 5, the fifth version of JavaScript, released in 2009.

  2. ES6 is the abbreviation of ECMAScript 6, also known as ES2015, is the sixth version of JavaScript, released in 2015.

  3. Compared with ES5, ES6 has added many new syntaxes and features, including arrow functions, let and const keywords, template strings, destructuring assignments, classes and modules, etc.

  4. These new features make JavaScript more modern, easy to read and write, and more maintainable.

  5. ES2015 is another name for ES6 because at the time of publication, the ECMAScript committee decided to rename ES6 to ES2015 to reflect the year it was released. Since ES2015, ECMAScript has released a new version every year, so ES6 can also be regarded as the first version of ES2015.

109. What is the function of let? Why use let with var?

  1. Both let and var are keywords used to declare variables, but they have some differences.

  2. Scope: Variables declared using var are function scope or global scope, while variables declared using let are block-level scope. Block-level scope means that variables declared inside curly braces such as if statements, for loops, and functions are only valid inside the curly braces.

  3. Variable promotion: Variables declared using var will undergo variable promotion, that is, the variable can be used before the declaration, but the value is undefined. Variables declared using let will not be promoted, that is, an error will be reported if used before the declaration.

  4. Repeated declaration: Variables declared using var can be declared repeatedly, and the latter declaration will override the previous declaration. Variables declared using let cannot be declared repeatedly in the same scope.

110. Give some common upgrades and optimizations for String strings in ES6?

  1. Template strings: Use backticks (`) to create string templates where variables or expressions can be inserted, making them easier to read.

  2. String extension methods: ES6 provides many new string methods, such as startsWith(), endsWith(), includes(), repeat(), etc., to make string operations more convenient.

  3. Destructuring assignment: You can use destructuring assignment to split a string into individual characters or substrings, which is more flexible.

  4. String traverser interface: ES6 adds a traverser interface to strings, which can use for...of loops to traverse each character in a string.

  5. Unicode support: ES6 supports Unicode character set, you can use \u or \u{} to represent Unicode characters, and also provides some new Unicode-related methods, such as codePointAt(), String.fromCodePoint(), etc.

  6. Regular expression upgrade: ES6 upgrades regular expressions, adds the u modifier, supports the processing of Unicode characters, and also provides new regular expression methods, such as sticky, flags, etc.

111. Give some common upgrades and optimizations for the Array array type in ES6?

  1. Spread Operator (Spread Operator): An array can be expanded into multiple parameters, or multiple parameters can be combined into an array.

  2. Array.from() method: You can convert an array-like object or an iterable object into an array.

  3. Array.of() method: You can convert a set of values ​​into an array.

  4. find() and findIndex() methods: You can find a qualified element in an array and return its value or index.

  5. includes() method: You can determine whether an element is contained in the array.

  6. fill() method: All elements in the array can be filled with the specified value.

  7. flat() and flatMap() methods: You can expand nested arrays into one-dimensional arrays and perform specified operations on each element.

  8. The initial value parameter of the reduce() method: You can specify the initial value of the reduce() method to avoid errors when the array is empty.

  9. Arrow function and forEach() method: can simplify the traversal operation of the array. 10. The return value of the map(), filter() and reduce() methods: These methods can be called in chains to make the code more concise and easy to read.

Guess you like

Origin blog.csdn.net/tianyhh/article/details/129814448