2023 Web front-end interview questions and answers (2)

1. Briefly describe the understanding of BFC, how to create BFC and its functions

BFC - Block Formatting Context (BFC) is part of the visual CSS rendering of the Web page. It is the area where block-level boxes are generated during the layout process, and it is also the limited area for interaction between floating elements and other elements.

Conditions for creating BFC :

  • Root element: body;
  • Element setting float: float value other than none;
  • Elements set absolute positioning: position (absolute, fixed);
  • Display values ​​are: inline-block, table-cell, table-caption, flex, etc.;
  • Overflow values ​​are: hidden, auto, scroll; 

BFC function

  • Prevent margins from overlapping. The margins of sub-elements belonging to the same bfc caused by bfc overlap (the vertical distance of the Box is determined by the margin. The margins of two adjacent Boxes belonging to the same BFC will overlap). We can wrap a container outside the div, And trigger the container to generate a BFC. Then the two divs do not belong to the same BFC, and margin overlap will not occur.
  • Clear the impact of floating: Block-level child elements are floating. If the block-level parent element does not set a height, its height will collapse. Reason: After the child elements are floated, BFC is turned on, and the parent element will not be expanded by the child elements. Solution: When calculating the height of BFC, floating elements also participate in the calculation. So just set the parent container to bfc to include the child elements: this container will contain the floated child elements, and its height will expand to contain its child elements, so in this BFC these elements will go back to the page regular document flow.
  • Prevent text wrapping

2. What are the ways to delay loading of Javascript scripts?

 1. Asynchronous Loading

Load JavaScript files asynchronously by adding the "async" attribute to avoid blocking the downloading and rendering of other resources during page load. Asynchronous loading does not guarantee the execution order of scripts, but is suitable for independent components and tool libraries.

<script src="../test.js" async/>

2. Deferred Loading

Delay loading of JavaScript files by adding the "defer" attribute to ensure that other resources on the page are loaded and rendered first. Unlike asynchronous loading, lazy loading ensures that scripts are executed in the order in which they appear, so it is more suitable for components and dependent libraries that need to be loaded in order.

<script src="../test.js" defer="defer"/>

3. Dynamic Loading

Dynamically add or remove HTML tags via JavaScript code to load or unload script files. This approach is suitable for situations where components and functionality need to be loaded and unloaded based on user behavior or business needs.

4. Lazy Loading

Load JavaScript files when needed, not when the page initially loads. Lazy loading can reduce the size and load time of the initial page and optimize the user experience. Usually lazy loading is suitable for images, videos, advertisements and some non-critical JavaScript code.

3. Use 5 to randomly select 10 numbers between 10 and 100, store them in an array, and sort them

    function randomNub(arr,len,min,max){
        //如果给的长度大于取值范围,则超出提示
        if(len>=(max-min)){
            return "超过"+min+"-"+max+"之间的个数范围"+(max-min-1)+"个的总数";
        }
        //从小到大排序,实现该数组的降序排列
        if(arr.length>=len){
            arr.sort(function(a,b){
                return a-b;
            });
            return arr;
        }
        //定义当前的数字
        var nowNub=parseInt(Math.random()*(max-min-1))+(min+1);
        //当生产的随机数==数组中的一个数字时,
        for(var j=0;j<arr.length;j++){
            if(nowNub==arr[j]){
                randomNub(arr,len,min,max);
                return;
            }
        }
        arr.push(nowNub);
        randomNub(arr,len,min,max);
        return arr;
    }
    var arr=[];
    //调用该函数,实现功能
    console.log(randomNub(arr,10,10,100))

4. JS implements a deep copy

Deep copy : A new composite array or object will be constructed, and the copy will continue when encountering the reference data type pointed to by the reference.

Shallow copy : refers to copying only the first level of an object or array, and other levels copy the stored memory address.

方式一:通过JSON对象的stringify和parse方法实现
let obj = {

name: '小红',

age: 13,

arr: [3, 4],

}

let obj1= JSON.parse( JSON.stringify(obj) )

方式二:jquery的extend()方法进行深拷贝(推荐在JQ中使用)
仅适用于JQuery构建的项目。JQuery自身携带的extend
let newObj = $.extend(true, {}, obj);
 //拷贝完成obj.b = 20;console.log(newObj.b); //输出 4

5. Please extract the results ["2023","09","15","09","10","23"] from "2023-09-15T09:10:23 Europe/Paris"

    let str = '2023-09-15T09:10:23 Europe/Paris';
    let arr2 = str.match(  /\d{1,}/g);

// \d:返回的是数字
// {1,} 至少返回的是由一个长度的数据

6. Implement a bind function

Explanation from the official website: The bind() method creates a new function. When bind() is called, this of this new function is specified as the first parameter of bind(), and the remaining parameters will be used as parameters of the new function. used when calling.

  • 1. Bind is an attribute of Function.prototype in the Function prototype chain. It is a function that modifies the this pointer, merges the parameters and passes them to the original function, and the return value is a new function.
  • 2. The function returned by bind can be called through new. At this time, the provided this parameter is ignored and points to the new object generated by new. The internal simulation implements the new operator.

accomplish:

First implement the simplest one fn.bind(context). As mentioned earlier, bindthe function will return a function. This function thisis what you pass in context. Then we can return a callfunction that is called. But what needs to be noted here is that because bindthe calling method itself is fn.bind(context), then bindThere is actually one inside the function , thisthis thisis fn, don’t contextconfuse it with:

 

② Implementation fn.bind(context, p1, p2): This requirement is very simple. We only need to bindpass all the parameters received by the function except the first parameter into the internally returned function, as follows

Implementation fn.bind(context, p1, p2)(p3, p4), this requirement is similar to the second requirement, except that the position where the parameters are received becomes the bindreturned function, then you only need to pass the parameters of the returned function into it this.call

7. Describe the Eventloop mechanism

The event loop is a way of executing code asynchronously, which enables JavaScript to handle concurrent events in a single-threaded execution environment. When an asynchronous event is encountered, it will be placed in the event queue EventQueue to wait for execution, and will be taken out and executed by Eventloop when appropriate. EventLoop is a continuously running process that will constantly check whether the event in the event queue needs to be executed. If The event will be taken out and executed until there are no events in the event queue.

The event loop mechanism helps us write efficient asynchronous code without worrying about thread synchronization and locking issues, because the Javascript engine will automatically handle them.

8. Briefly describe the differences between MVC, MVP, and MVVM

The full name of MVC is Model View Controller, which is the abbreviation of model-view-controller. It is a software design model that organizes code using a method that separates business logic, data, and interface display. The business logic is gathered into a component, and there is no need to rewrite the business logic while improving and personalizing the interface and user interaction. MVC was uniquely developed to map traditional input, processing, and output functions into a logical graphical user interface structure.

 MVP pattern  : Model-View-Presenter; MVP evolved from the classic pattern MVC. Their basic ideas are similar. Controller/Presenter is responsible for logic processing, Model provides data, and View is responsible for display.

MVVM is the abbreviation of Model-View-ViewModel. It is essentially an improved version of MVC. MVVM abstracts the state and behavior of the View, allowing us to separate the view UI and business logic. Of course, ViewModel has already done these things for us. It can take out the data of the Model and help handle the business logic involved in the View due to the need to display content. Microsoft's WPF brings new technical experiences, such as Silverlight, audio, video, 3D, animation..., which results in the software UI layer being more detailed and customizable. At the same time, at the technical level, WPF also brings new features such as Binding, Dependency Property, Routed Events, Command, DataTemplate, ControlTemplate and so on. The origin of the MVVM (Model-View-ViewModel) framework is a new architectural framework that evolved from the application method of combining the MVP (Model-View-Presenter) pattern with WPF. It is based on the original MVP framework and incorporates the new features of WPF to cope with increasingly complex changes in customer needs.

9. Describe the life cycle execution sequence of parent and child components

1. Loading and rendering process
parent beforeCreate->parent created->parent beforeMount->child beforeCreate->child created->child beforeMount->child mounted->parent mounted 2.
Child component update process
parent beforeUpdate->child beforeUpdate->child updated->parent updated
3. Parent component update process
parent beforeUpdate->parent updated
4. destruction process
parent beforeDestroy->child beforeDestroy->child destroyed->parent destroyed

10. Describe the principle of Vue two-way data binding

The principle of two-way data binding : using "data hijacking" combined with the "publisher-subscriber" model, using the "Object.defineProperty()" method to hijack the setters and getters of each property, and publish messages to subscribers when the data changes Or, trigger the corresponding listening callback.

Implementation process

We already know that to implement two-way binding of data, we must first hijack and monitor the data, so we need to set up an Observer to monitor all properties. If the attribute changes, you need to tell the subscriber Watcher to see if it needs to be updated. Because there are many subscribers, we need a message subscriber Dep to specifically collect these subscribers, and then manage them uniformly between the Observer and the Watcher. Next, we also need an instruction parser Compile to scan and parse each node element, initialize the relevant instructions into a subscriber Watcher, and replace the template data or bind the corresponding function. At this time, when the subscriber Watcher Upon receiving the change of the corresponding attribute, the corresponding update function will be executed to update the view. Therefore, we next perform the following three steps to achieve two-way binding of data:

1. Implement a listener Observer to hijack and monitor all properties. If there is any change, the subscriber will be notified.

2. Implement a subscriber Watcher that can receive property change notifications and execute corresponding functions to update the view.

3. Implement a parser, Compile, which can scan and parse the relevant instructions of each node, and initialize the template data and corresponding subscribers according to the initialization.

11. How to monitor array changes in vue2?

In Vue 2, the bottom layer is to monitor changes in the array by overriding the prototype method of the array.

Specifically, when calling the mutation methods of the array (such as push, pop, shift, unshift, splice, sort, and reverse), Vue will perform the following steps:

  1. Call the original array method and perform corresponding mutation operations on the array.

  2. After performing the mutation operation, Vue will trigger a notification to notify related dependencies (such as views) to update.

  3. During the notification process, Vue will traverse all the observers (Observer) of the array and call their update methods to update related dependencies.

In this way, Vue can capture changes in the array in real time and update related dependencies in a timely manner, thereby achieving monitoring and response to the array.

It should be noted that Vue 2 can only detect changes to the array through mutation methods, but cannot detect changes to the array by directly modifying an element of the array or using non-mutation methods (such as filter, concat, etc.). If you need to monitor these non-mutated array changes, you can use the watch option or the $watch method to manually monitor the array changes.

12. How does vue-router define dynamic routing? How to obtain the passed dynamic parameters?

Definition: In the index.js file in the router directory, add /:id to the path attribute. 

Use the params.id of the router object. For example: this.$route.params.id

Get parameters: $route  is a "routing information object", including path, params, hash, query, fullPath, matched, name and other routing information parameters.

13. Describe what NextTick does in Vue?

Official definition: Execute a delayed callback after the next DOM update cycle. Use this method immediately after modifying the data to get the updated DOM.

DOM operations performed in the created() hook function of the Vue life cycle must be placed in the callback function of Vue.nextTick()

Used Vue.nextTick()to obtain the updated DOM.
Trigger timing: After the data changes in the same event loop, the DOM completes the update and Vue.nextTick()the callback is executed immediately.

Guess you like

Origin blog.csdn.net/weixin_41620505/article/details/132894639