MOOC 1299 front-end interview questions - knowledge breadth and depth day06

depth of knowledge interview questions

- My blog needs to be viewed on a narrower page, and the pictures cannot be displayed equally, sorry.

1. How to detect JS memory leak? What are the scenarios?

  • JavaScript memory leaks refer to the problem that a variable or object still exists in memory when it is not needed to be used, resulting in high memory usage. Detecting JavaScript memory leaks can use the following methods:
  1. Memory snapshots: Use Chrome's developer tools or Node.js' heapdump module to generate memory snapshots and analyze their contents to find out which objects are taking up too much memory space.

  2. Resource monitoring: Use the browser's Performance API or Node.js' process.memoryUsage() method to monitor the memory usage of the application, as well as resource loading and release.

  3. Code review: Through static or dynamic code analysis, detect whether there are obvious risks of memory leaks, such as unclosed files, uncleaned timers or event listeners, etc.

  4. Memory analysis tools: Use professional memory analysis tools such as Memory Analyzer Tool (MAT), Heap Profiler in Chrome DevTools, etc. to help developers find the root cause of memory leaks.

具体检测方法怎么使用,直接问chatgpt,它回答很全面

Common JavaScript memory leak scenarios include:

  1. The timer is not cleared: When using the setInterval or setTimeout method to create a timer, if it is not cleared in time, the callback function will always occupy memory. For example:
var timer = setInterval(function() {
    
    
  // do something
}, 1000);

// 及时清除定时器
clearInterval(timer);

在使用定时器之后,一定要记得及时清除。

  1. Closure is not released: If external variables are referenced in the closure and the closure is no longer needed, the external variables will still be kept in memory and not released. For example:
function init() {
    
    
  var name = 'John';

  return function() {
    
    
    console.log(name);
  };
}

// 访问闭包函数并返回一个新的函数
var sayHello = init();

// 执行完毕闭包函数之后,手动解除对name变量的引用
sayHello = null;

在使用闭包时,一定要确保不再需要引用外部变量时,解除闭包对该变量的引用

  1. Circular reference: When two objects refer to each other and the reference relationship is not dereferenced in time, neither object will be garbage collected, resulting in a memory leak. For example:
var obj1 = {
    
    };
var obj2 = {
    
    };

obj1.obj2 = obj2;
obj2.obj1 = obj1;

// 手动解除obj1对obj2的引用
obj1.obj2 = null;

避免循环引用的最佳方法是避免相互引用。如果无法避免,可以通过手动解除其中一个对象对另一个对象的引用来解决问题。

  1. DOM nodes are not removed: When dynamically generating DOM nodes, if the nodes are not removed from the document tree in time, the nodes will always occupy memory and cannot be garbage collected. For example:
var container = document.getElementById('container');

// 在循环中动态生成DOM节点
for (var i = 0; i < 1000; i++) {
    
    
  var node = document.createElement('div');
  container.appendChild(node);
} // 如果不及时从文档树中移除这些节点,会导致内存泄漏

// 在不需要节点时,手动从文档树中移除它们
while (container.firstChild) {
    
    
  container.removeChild(container.firstChild);
}

在生成DOM节点时,一定要及时从文档树中移除节点。

  1. Large objects are not released: When large objects (such as large arrays) are created in the program, if these objects are no longer needed, but are still kept in memory, memory leaks will result. For example:
var data = [];

// 创建1亿个随机数加入data数组
for (var i = 0; i < 100000000; i++) {
    
    
  data.push(Math.random());
}

// 不再需要data数组时,手动将其置为null
data = null;

当不再需要大对象时,可以手动将它们置为null,以便让垃圾回收器及时回收它们的内存。

2. Common memory leaks in vue and solutions

<script>
export default {
    
     
    name :'Memory Leak Demo',
    data:{
    
    
      return {
    
    
         arr:[10,20,30] // 数组 对象
         intervalId:0 // 接住定时器,防止内存泄漏
      }
    },
    methods:{
    
    },
    mounted(){
    
     
         // 全局变量,有内存泄漏
         window.arr = this.arr
         // 全局事件,有内存泄漏
         window.printArr = () =>{
    
    
               console.log(this.arr)
         }
         // 使用intervalId接住定时器防止内存泄漏
         this.intervalId = setInterval(()=>{
    
    
            console.log(this.arr)
         },100)
    },
    // vue2中 使用 beforeDestroy
    beforeUnmount(){
    
     
          // 清除全局变量
          window.arr = null
          // 清除全局事件
          window.printArr = null
          // 清除定时器
          if(this.intervalId){
    
    
              clearInterval(this.intervalId)
          }
    }
}
</script>
<script>
export default {
    
     
    name :'Memory Leak Demo',
    data:{
    
    
      return {
    
    
         arr:[10,20,30] // 数组 对象
      }
    },
    methods:{
    
    
         printArr(){
    
     // 事件
             console.log(this.arr)
         }
    },
    mounted(){
    
     
        // 监听事件
        window.addEventListener('resize',this.printArr)   
    },
    // vue2中 使用 beforeDestroy
    beforeUnmount(){
    
     
        // 移除事件 
        window.removeEventListener('resize',this.printArr) 
    }
}
</script>

3. Briefly describe the jS mark removal method?

Mark and Sweep is a common garbage collection algorithm used to automatically identify and release unused memory in programs that allocate dynamic memory.

  • This algorithm has three steps:
  1. Marking phase: Starting from the known "root" object in the program, traverse all accessible objects and mark them to indicate that they are being used.

  2. Cleanup phase: traverse the entire heap (that is, the memory space used by the program) and delete unmarked objects.

  3. Compaction phase (optional): All remaining objects are moved to one end of the heap to make more room for new objects.

For example, suppose we have a JavaScript program that uses many objects. When an object becomes no longer needed, the JavaScript interpreter uses the mark-and-sweep algorithm to clear it from memory so that the memory can be used for other purposes. The working principle of the mark-and-sweep algorithm is to mark all objects that are currently in use, and then delete the objects that have not been marked.
insert image description here

4. Traversing an array, which is faster, for or forEach?

  • In JavaScript, both for and forEach can be used to iterate over an array.
  1. In general, using a for loop is faster than forEach, because a for loop is a native JavaScript syntax construct, while forEach is a function call.
  2. In practice, the difference is not that big, and for small arrays the performance of both methods is almost the same.
const arr = [1, 2, 3, 4, 5];

console.time('for loop');
for (let i = 0; i < arr.length; i++) {
    
    
  console.log(arr[i]);
}
console.timeEnd('for loop');

console.time('forEach loop');
arr.forEach((item) => {
    
    
  console.log(item);
});
console.timeEnd('forEach loop');
  1. We use the console.time() and console.timeEnd() methods to measure the elapsed time of the for loop and the forEach loop.
  2. We output the elements of the array arr to the console one by one. After running this code, we see that the for loop takes less time to run than the forEach loop.
  3. Although the for loop may be faster than the forEach loop, the forEach loop is more concise and readable, so in some cases, using forEach can improve the readability and maintainability of the code.
    insert image description here

5. In which life cycle should Ajax be placed in vue?

  1. created() life cycle function: Ajax request can be called immediately after the component instance is created. At this point, the component's DOM is ready, but not yet mounted on the page.

  2. mounted() life cycle function: Ajax request can be called immediately after the component is mounted on the page. At this point, the DOM of the component has been rendered, and the DOM elements can be obtained through the selector.

  3. activated() lifecycle function: called when the component is activated, for example in a dynamic component wrapped with keep-alive. At this point, the DOM of the component has been rendered, and operations such as Ajax requests can be performed.

Putting in that life cycle will be faster

  • If you only consider the speed of Ajax requests, it is indeed faster to make Ajax requests in the created() lifecycle function. Because in the life cycle of the Vue component, the created() function will be called immediately after the instance is created, and the mounted() function will be called when the component is mounted on the page.
  • It will be faster to put the Ajax request mounted()inside. Because in mounted()the life cycle function, the component has been mounted on DOM树the , it can be operated immediately at this time DOM, and the user can also see the rendered interface, which can improve the user experience.
  • In created()the life cycle function, the component instance has been created, but it has not been mounted on it DOM树. At this time, there is no guarantee that the element is fully prepared, and problems may occur DOMif it is involved .DOM操作

6. What is the difference between the VUE3 Composition API life cycle?

insert image description here
insert image description here

7. What is Vue-router's MemoryHistory (abstract)?

insert image description here
insert image description here

8. What is the difference between the diff algorithm in vue2 and vue3?

insert image description here
insert image description here
insert image description here
insert image description here

  • Vue2's diff algorithm. See the following chatgpt answer
    insert image description here
    insert image description here

  • Vue3's diff algorithm
    insert image description here
    insert image description here

9. H5 click on the mobile terminal has a 300ms delay, how to solve it?

insert image description here
insert image description here
insert image description here

insert image description here

10. What is the difference between token and cookie in network requests?

insert image description here
insert image description here
insert image description here
insert image description here

insert image description here

11. What is the difference between script tag, defer and async? (important!)

insert image description here

insert image description here
insert image description here

insert image description here

12. What is the difference between :prefetch and dns-prefetch? What is the difference between preload and prefetch?

insert image description here
insert image description here
insert image description here
insert image description here

13. What are the front-end attack methods? How to prevent it?

XSS attack

insert image description here
insert image description here

CSRF attack

insert image description here

clickjacking attack

insert image description here
insert image description here

DDoS attack

insert image description here

SQL injection attack

insert image description here

insert image description here
insert image description here

Summarize

insert image description here
insert image description here

14. What is the difference between WebSocket and HTTP?

insert image description here

  • Create a server and download dependent packages
  1. npm init -y
  2. npm install ws --save
  3. npm install nodemon --save-dev
  4. yarn dev run

insert image description hereinsert image description hereinsert image description here
insert image description here
insert image description here
insert image description here

multiplayer communication

insert image description here
insert image description here
insert image description here

15. What is the difference between WebSocket and HTTP long polling?

insert image description here
insert image description here

insert image description here

16. Describe the complete process from inputting url to page display?

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

17. What is the difference between repaint and reflow?

insert image description here
insert image description here

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

The following is a detailed explanation and optimization scheme.

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

18. How to implement multi-tab communication on web pages

insert image description here

insert image description here
insert image description here

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

19. How to realize the communication between webpage and iframe?

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

20. How to optimize the H5 page for the first screen?

insert image description here
insert image description here
insert image description here

insert image description here
insert image description here
insert image description here
insert image description here

21. The background returns 100,000 pieces of data at one time. how do you render

insert image description here

insert image description here

22. What are the commonly used design patterns and usage scenarios for the front end?

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

insert image description here
Proxy mode reference proxy, link address
insert image description here

Decorator pattern reference, link address
insert image description here

23. Continuing from the previous question, what is the difference between observer mode and publish-subscribe mode?

insert image description here
insert image description here
insert image description here

  • Observer mode : Subject and Observer are directly bound without intermediary. Such as addEventListener
  • Publish and subscribe : Publisher and Observer do not know each other and need an intermediary Event Channel. Such as EventBus custom events.

24. What Vue optimizations have you done in your actual work?

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

  • The route is lazy loaded, and the project is relatively large. Split the route to ensure that the home page is loaded first.
import {
    
     createRouter, createWebHistory } from 'vue-router'

const routes = [
    {
    
    
      path: '/',
      name: 'Home',
      component: () => import('../views/Home.vue')
    },
    {
    
    
      path: '/about',
      name: 'About',
      component: () => import('../views/About.vue')
    },
    // ...
  ]
  
const router = createRouter({
    
    
      history:createWebHistory(),
      routes
})

export default router

insert image description here
insert image description here
insert image description here

25. What pitfalls have you encountered in the process of using vue?

insert image description here
insert image description here
insert image description here

26. How to uniformly monitor Vue component error reporting?

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

insert image description here
insert image description here

insert image description here
insert image description here

27. How do you troubleshoot performance issues if a H5 is slow?

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

27. Lighthouse, a very popular third-party performance evaluation tool.

  • Support PC and mobile terminal
  • Install in npm i lighthouse -g project
  • lighthouse https://URL to be tested --view --preset=desktop
  • The mobile terminal is tested by default, and the PC terminal needs to be tested by adding --preset=desktop

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/weixin_46426412/article/details/130747025