Collection of front-end interview questions

cross domain

Cross-domain: First of all, the same origin refers to the same "protocol + domain name + port". Even if two different domain names point to the same ip address, they are not of the same origin. jsonp, the src attribute of the iframe tag, and the front-end nginx configuration reverse proxy , nodejs middleware proxy cross-domain or set cors to allow all domain names to access, the front end uses the proxy option in webpack devserver to set the proxy, websocket is not restricted by the same-origin policy.

This-oriented

In the global scope, this refers to the global object (usually the window object in a browser environment).
In a function, the value of this depends on how the function was called.
If the function is invoked as a method of an object, this points to the object on which the method was invoked.
If the function is called as an ordinary function, this points to the global object (in non-strict mode) or undefined (in strict mode).
If the function is invoked via the call, apply, or bind method, this points to the object specified by the first parameter of the call, apply, or bind method.
If the function is called as a constructor (using the new keyword), this points to the newly created object.
In the arrow function, the value of this is inherited from the outer scope, and it will not change due to changes in the calling method.

scope

The scope chain is a mechanism for finding variables and functions, which is a chain structure composed of the variable objects of the current execution environment and all its parent execution environments. When a variable or function is accessed in an execution environment, it will first search in the variable object of the current execution environment. If it cannot be found, it will search up the scope chain until it finds the corresponding variable or function, or reaches the final value. The outer global object (such as window).
The creation of the scope chain is determined when the function is defined, and it is related to the definition position of the function. When the function is called, a new execution environment is created, which contains a new variable object, and it is added to the front of the scope chain. In this way, the inside of the function can access the variables and functions in its scope and its outer scope, forming a scope chain.

prototype chain

Each object will initialize a property inside it, which is __proto__. When we access the property of an object,
if this property does not exist inside the object, then he will go to __proto__ to find this property, and this __proto__ You will have your own __proto__, so you keep looking for it like this, which is what we usually call the concept of the prototype chain. According to the standard, proto is not open to the public, that is to say, it is a private property
relationship: instance.constructor.prototype == instance.proto

TS implements the interface

export interface ICategoryList {
    
    
    id:               number;
    name:             string;
    pid:              number;
    gmt_create:       string;
    gmt_modified:     string;
    level:            Level | null;
    subCategoryList?: ICategoryList[];
}

position

The position attribute is used to control the positioning of elements. Common values ​​include:

static: The default value, indicating that the element is normally positioned in the document flow and will not be affected by the top, right, bottom, and left attributes.
Relative: generate relatively positioned elements, and position them relative to their normal positions. Adjust the position of the element by setting the top, right, bottom, and left attributes. It will not break away from the document flow, and the surrounding elements will still be arranged according to the normal layout.
absolute: Generate absolutely positioned elements, positioned relative to the nearest non-static positioned parent element, or relative to the document root element (ie, the browser window) if there is no non-static positioned parent element. Absolutely positioned elements will break away from the document flow and do not occupy space. You can precisely control the position of the element by setting the top, right, bottom, and left attributes.
fixed: Generate absolutely positioned elements, positioned relative to the browser window, and will not change position as the page scrolls. You can specify the position of the element by setting the top, right, bottom, and left attributes.
inherit: Specifies to inherit the value of the position attribute from the parent element.

For relative and absolute positioning, the origin (coordinate datum) is the element's position in the normal document flow. By adjusting the top, right, bottom, and left properties, you can offset horizontally and vertically relative to the origin to achieve precise positioning of elements.

css implements two-column layout

//	左边定宽,右边自适应方案
float + margin,float + calc

/* 方案1 */ 
.left {
    
    
  width: 120px;
  float: left;
}
.right {
    
    
  margin-left: 120px;
}
/* 方案2 */ 
.left {
    
    
  width: 120px;
  float: left;
}
.right {
    
    
  width: calc(100% - 120px);
  float: left;
}

flex layout

display: flex;
// 容器的6个属性:
flex-direction、flex-wrap、flex-flow、justify-content、align-items、align-content

flex-direction属性有4个值
row(默认值):主轴为水平方向,起点在左端(项目从左往右排列)。
row-reverse:主轴为水平方向,起点在右端(项目从右往左排列)。
column:主轴为垂直方向,起点在上沿(项目从上往下排列)。
column-reverse:主轴为垂直方向,起点在下沿(项目从下往上排列)。

https://blog.csdn.net/wwwjjjjj666/article/details/128033184

BOM and DOM

BOM (Browser Object Model) provides an interface to interact with the browser window, such as operating browser history, timers, etc.

window.location.href = "https://www.example.com";
let screenWidth = window.screen.width;
let timer = setTimeout(function() {
    
    
   console.log("Timer expired");
}, 5000);

DOM is an interface for JavaScript to manipulate the content and structure of web pages. You can add, delete, modify, and query web page elements through DOM

let element = document.getElementById("myElement");
element.innerHTML = "New content";

let newElement = document.createElement("div");
newElement.textContent = "Dynamic element";
document.body.appendChild(newElement);

Stabilization and throttling

The principle of the anti-shake function: Merge the events that trigger very frequently into one execution. Only execute the callback function once within the specified time. If the event is triggered again within the specified time, the execution time of the callback function will be restarted based on this moment.
Applicable scenario:
verification of text input, send AJAX request for verification after continuously inputting text, just verify once.
Button submission scenario: prevent multiple button submissions, only execute the last submitted
server verification scenario: form verification requires the cooperation of the server, Only execute the last time of a continuous input event, and the function of searching association words is similar to the
principle of throttling function: when events are triggered frequently, the event callback will only be executed within the specified time period, that is, the interval between trigger events is greater than or equal to the specified time The callback function will be executed. To sum it up: events are triggered at intervals of a period of time.
Applicable scene:

Drag and drop scene: Execute only once within a fixed period of time to prevent ultra-high frequency trigger position changes. The drag and drop function of DOM elements realizes (mousemove)
zooming scene: monitor browser resize
scrolling scene: monitor the scrolling scroll event to judge whether to automatically load more at the bottom of the page
animation scene: avoid performance problems caused by triggering animation multiple times in a short period of time

bubble order

The event flow is divided into three phases: the capture phase, the target phase, and the bubbling phase.

Capture Phase: The event passes down from the outermost parent node until it reaches the parent node of the target element. During the capture phase, the event passes through the parent, grandparent, etc., but no event handlers are triggered.
Target Phase: The event arrives at the target element itself, triggering the event handler on the target element. If an event has multiple handlers bound to the target element, they will be executed in the order they were added.
Bubble Phase: The event bubbles up from the target element, passed to the parent node, until passed to the outermost parent node or the root node. During the bubbling phase, the event triggers the event handlers of the parent node, grandparent node, etc. in turn.

Cookie function

A cookie is data (usually encrypted) stored on the user's local terminal (Client Side) by the website to identify the user's identity. The cookie data is
always carried in the same-source http request (even if it is not required), and it will be recorded between the browser and the server. Passing
sessionStorage and localStorage back and forth will not automatically send the data to the server, but only save it locally. Storage
size:
The cookie data size cannot exceed 4k.
Although sessionStorage and localStorage also have storage size restrictions, they are much larger than cookies, and can reach 5M or larger
Expiration time:
localStorage stores persistent data, and the data will not be lost after the browser is closed unless the data is actively deleted.
sessionStorage data will automatically delete the cookie after the current browser window is closed. The
set cookie expiration time will remain valid even if the window or browser is closed

User permissions in vue

Interface authority
After the user logs in successfully, he can get a token, save the token, and intercept it through the axios request interceptor. The request header must carry the token
menu authority and the backend returns to the menu.
Button authority
Button authority can also be judged by v-if

Publish-Subscribe Pattern:

Pros: Decouples publishers and subscribers so they can change independently. Increased code flexibility and maintainability.
Disadvantage: It may cause publishers to overpublish messages, causing performance problems. Subscribers need logic related to subscription and unsubscription.
Applicable scenario: When there is a one-to-many relationship and the state change of one object needs to notify multiple other objects, the publish-subscribe mode can be used.

The difference between synchronous and asynchronous

Synchronization: the browser accesses the server request, the user can see the page refresh, resend the request, wait for the request to complete, the page refreshes, new content appears, the user sees the new content, and proceeds to the next step Asynchronous: the browser accesses the server request, the user operates
normally , the browser backend makes the request. After the request is completed, the page will not be refreshed, and new content will appear, and the user will see the new content.
Common asynchronous operations include network requests (Ajax), timers (setTimeout, setInterval), event processing, and so on. In these asynchronous operations, the execution of the task will not block other parts of the program, but will be performed in the background. When the task is completed, the program will be notified to proceed to the next step through a callback function or event.

Summary: Synchronous operation is to execute tasks in sequence; asynchronous operation is to execute tasks through callback functions or event triggers, which will not block the execution of the program, and improve the concurrency and responsiveness of the program. In actual development, asynchronous operations are usually used to process time-consuming operations and tasks that need to wait for results to improve program performance and user experience.

The difference between websocket and ajax

What they have in common: Both Ajax and websocket are tools for front-end and back-end data communication;
1. Different life cycles.
Websocket is a long-term connection, and the session is always maintained.
Ajax is a short connection, and the sender will disconnect after receiving it.
2. Scope of use
websocket is suitable for real-time interaction data between front and back ends.
Ajax is non-real-time interactive data.
3. The initiator
websocket is the mutual push between the server and the client.
Ajax is initiated by the client.

The difference between axios and ajax

Axios is an encapsulation of ajax technology through promise, just like jQuery implements ajax encapsulation.
To put it simply: ajax technology realizes partial data refresh of web pages, and axios realizes the encapsulation of ajax.
Ajax is a general term for technology, based on native XHR development, there is already an alternative to fetch.
fetch is a native API for network requests and supports Promise API, but its functions are relatively simple in some aspects, and it needs to be encapsulated to handle errors, timeouts, etc.

The difference between ref and refs

ref acts on the component: get the information of the sub-component
this.$refs get the information of the sub-component

div centered horizontally and vertically

/** 1 **/
.wraper {
    
    
  position: relative;
  .box {
    
    
    position: absolute;
    top: 50%;
    left: 50%;
    width: 100px;
    height: 100px;
    margin: -50px 0 0 -50px;
  }
}

/** 2 **/
.wraper {
    
    
  position: relative;
  .box {
    
    
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}

/** 3 **/
.wraper {
    
    
  .box {
    
    
    display: flex;
    justify-content:center;
    align-items: center;
    height: 100px;
  }
}

/** 4 **/
.wraper {
    
    
  display: table;
  .box {
    
    
    display: table-cell;
    vertical-align: middle;
  }
}

horizontal centering method

The element is an inline element, set the parent element text-align:center
If the element width is fixed, you can set the left and right margins to auto;
absolute positioning and movement: absolute + transform
use flex-box layout, specify the justify-content attribute as center and
set the display to tab -cell

The method of vertical centering

Set the display mode to table, display: table-cell, and set vertical-align: middle
uses flex layout, set to align-item:
set bottom: 0, top: 0 in center absolute positioning, and set margin: auto
absolute positioning Set top:50% when the height is fixed in the middle, and the margin-top value is a negative value of half the height. The
text is vertically centered
. Set line- height to the height value. Its vertical alignment is middle to achieve vertical centering

The role of vue's $nexttick

nextTick allows us to execute a delayed callback after the next DOM update cycle to get the updated DOM

The main difference between vue2 and vue3 lies in the following points:

1. Different lifecycle function hooks

2. The principle of two-way data binding is different

3. Define variables and methods are different

4. The use of instructions and slots is different

5. Different API types
Vue2 option API (separate different attributes in the code: data, computed, methods, etc.)

Vue3 combined api (use methods to separate, which is more convenient and tidy)

6. Whether to support fragmentation
vue3 can have multiple root nodes

7. The parameters passed between father and son are different

8. Some settings in the main.js file are different

The difference between vue3's ref and reactive

ref
ref is the same as reactive
: create a reactive object.
Different:
reactive must accept an input parameter in the form of an object, while ref can be in the form of an object or a single value.
Reading/assignment is different, ref must read the value from the .value attribute
ref has an asynchronous problem
toRef and toRefs:
toRefs will only generate a ref for the property contained in the source object, and convert the object to a normal object without losing reference to the source The responsive link of the object, that is, modifying the attribute value of the source object, the corresponding attribute value (ref) of the generated new ordinary object will also be modified, and vice versa.
toRef creates a ref for a specific property, also maintaining responsive links.

The difference between watch and computed

Functionally: computed is a computed attribute, watch is to monitor a value change, and then execute the corresponding callback.

1. Whether to call the cache: the attributes on which the functions in computed depend have not changed, so when calling the current function, it will be read from the cache, and the watch will execute the callback every time the monitored value changes.

2. Whether to call return: functions in computed must use return to return, functions in watch do not have to use return.

3. Computed will start monitoring when it is loaded for the first time by default; watch will not monitor for the first time by default. If you need to monitor for the first time, add the immediate attribute and set it to true (immediate: true)

4. Usage scenario: computed-----When an attribute is affected by multiple attributes, use computed-----shopping cart product settlement. watch – When one piece of data affects multiple pieces of data, use watch-----search box.

Summary of the difference between watch and computed

Computed supports caching, and will only be recalculated when the dependent data changes; watch does not support caching, as long as the monitored data changes, the corresponding operation will be triggered

Computed does not support asynchronous operation. When there are asynchronous operations in computed, it is impossible to monitor data changes; watch supports asynchronous operations.

The attribute value of the computed attribute is a function, and the return value of the function is the attribute value of the attribute. Each attribute in computed can set the set and get methods. The data monitored by the watch must be the data declared in the data or the data in the props passed by the parent component. When the data changes, the listener is triggered

Talk about your understanding of ES6

ES6 (ECMAScript 2015) is the sixth major version of JavaScript, introducing many new language features and improvements to improve developer productivity and code quality. Following are some important features of ES6:

Block-level scope : The let and const keywords are introduced to allow variables to be declared in block-level scope, which solves the problems of variable promotion and scope pollution.
Arrow function : Use arrows (=>) to define functions, which simplifies the writing of functions and automatically binds this.
Template string : Use backticks (`) to wrap the string, and you can use variables and expressions in the string to achieve more flexible string splicing and formatting.
Destructuring assignment : Through the destructuring assignment syntax, values ​​can be extracted from arrays or objects and assigned to corresponding variables, which simplifies the operation of variable assignment.
Default parameters : Functions can define default parameter values, which simplifies the operation of passing parameters when the function is called.
Spread operator : Use three dots (…) to expand arrays and objects. You can split an array or object into independent elements, or combine multiple arrays or objects into one.
Promise : The Promise object is introduced to better handle asynchronous operations, solve the problem of callback hell, and provide a clearer asynchronous programming model.
Classes and modularity : ES6 introduces the concept of classes, which can be defined using the class keyword, achieving a method closer to traditional object-oriented programming. At the same time, ES6 also provides modular support, and modules can be imported and exported using import and export syntax.
Modularity: The concept of modularization is introduced, and modules can be imported and exported using import and export syntax, providing better code organization and module reuse.
Iterators and Generators **: The concepts of iterators and generators are introduced. You can use custom iterators to traverse data collections and use generator functions to generate iterators.
pipe operator: The feature of the proposal stage, which introduces the pipeline operator (|>), which can pass the result of an expression as a parameter to the next expression, which simplifies the writing of function calls and method chains.

How to create a block formatting context (block formatting context), what is the use of BFC

To create a Block Formatting Context (BFC), the following method can be applied:

1. Use the float attribute: Set the element's float attribute to a value other than none to create a BFC.
2. Use the overflow attribute: Set the overflow attribute of the element to a value other than visible, such as auto or hidden, to create a BFC.
3. Use the display attribute: Set the display attribute of the element to a specific value such as inline-block, table-cell, table-caption, etc., to create a BFC.
4. Use the position attribute: Set the element's position attribute to absolute, fixed, relative or sticky to create a BFC.
5. Use the contain attribute: Set the contain attribute of the element to layout to create a BFC (only applicable to some browsers).
Under IE, Layout can be triggered by zoom:1

The difference between BFC layout and ordinary document flow layout is ordinary document flow layout:

The height of floating elements will not be calculated by the parent.
Non-floating elements will cover the position of floating elements.
The margin will be passed to the parent element.
The margins above and below two adjacent elements will overlap.

Summary of array deduplication methods

Method 1. Use ES6 Set to deduplicate (most commonly used in ES6)
Method 2. Use for to nest for, and then splice to deduplicate (most commonly used in ES5)
Method 3. Use indexOf to deduplicate
method 4. Use sort() sorting method, Then traverse and compare adjacent elements according to the sorted results
Method 5, use includes
method 6, use hasOwnProperty
method 7, use filter
method 8, […new Set(arr)]

JS deep and shallow copy

Shallow copy
1. Use Object.assign() method
2. Use the spread operator
Deep copy

  1. Use recursion to implement deep copy functions
  2. Use the cloneDeep() method of the third-party library lodash
  3. Use JSON.parse(JSON.stringify()) to implement deep copy

microtasks and macrotasks

microtask
process.nextTick
promise
Object.observe
MutationObserver

Macro task
script
setTimeout
setInterval
setImmediate
I/O
UI rendering
The browser will first execute a synchronous task and then the macro task, and then execute the micro task first if there is asynchronous code

The difference between server-side rendering and client-side rendering

Server-side rendering: The DOM tree is generated on the server side and then returned to the front end.

Client-side rendering: the front-end goes to the back-end to fetch data to generate a DOM tree.
Advantages of server-side rendering:

1. Try not to occupy the resources of the front end, which takes less time and is faster.

2. It is conducive to SEO optimization, because there is a complete html page at the back end, so it is easier for crawlers to crawl information.

Disadvantages of server-side rendering:

1. It is not conducive to the separation of front and back ends, and the efficiency of development is reduced.

2. The analysis of html speeds up the front end, but increases the pressure on the server.

Advantages of client-side rendering:

1. The front and back ends are separated, and the development efficiency is high.

2. The user experience is better. We make the website into a SPA (single page application) or part of the content into a SPA. When users click, there will be no frequent jumps.

Disadvantages of client-side rendering:

1. The response speed of the front end is slow, especially the first screen, which is unbearable for users.

2. It is not conducive to SEO optimization, because the crawler does not know SPA, so it only records a page.

What is the difference between ts and js?

1. TS extends JS, introduces the concept of type into JS, and adds many new features.
2. The TS code needs to be compiled into JS by a compiler, and then executed by a JS parser.
3. TS is fully compatible with JS, in other words, any JS code can be directly used as JS.
4. Compared with JS, TS has static typing, stricter syntax, and more powerful functions;

TS can complete the code inspection before the code is executed, reducing the chance of runtime exceptions;
TS code can be compiled into any version of JS code, which can effectively solve the compatibility problem of different JS operating environments;
the same function, TS The amount of code is larger than that of JS, but because the code structure of TS is clearer and the variable types are clearer, TS is far better than JS in the maintenance of later code.

The difference between watch and watchEffect

Both can monitor data attribute changes.
Watch needs to specify which attribute to monitor
. watchEffect will automatically monitor its changes according to the attributes in it.

The difference between reactive and ref

1. In terms of defining data:

ref is usually used to define basic type data
and reactive is used to define: object (or array) type data
ref can also be used to define object or array type data, which will be converted to proxy objects through reactive internally.
2. From the principle aspect:
ref through Object The get and set of .defineProperty() implement data proxy.
Reactive uses Proxy to implement data proxy, and manipulates the data inside the source object through Reflect.
3. In terms of use:
ref requires .value to operate data, but not in template.
reactive is not required, value

おすすめ

転載: blog.csdn.net/u011313034/article/details/131438691