The collection of 2023 front-end interview questions (with answers) is being continuously updated...

js basic class

1. What is the prototype chain and the significance of the existence of the prototype chain

(1). What is the prototype chain

Answer: The prototype chain is that each object has a prototype object, and the object uses its prototype as a template and inherits methods and properties from the prototype. A prototype object may also have a prototype and inherit methods and properties from it, layer by layer, and so on. This relationship is called the prototype chain.
Simple understanding: the prototype chain is that if the definition cannot be found in the current object, it will continue to search on the prototype object of the current object until it is undefined.

(2). What is the significance of the existence of prototype and prototype chain?

Answer: Instance objects can share constructor prototype properties and methods to save memory. The more properties and methods on the constructor prototype, the greater the memory savings.

2. What is scope?

The scope is divided into: 1. Global scope, 2. Function scope, 3. Block-level scope

Answer: Scope is the accessibility of variables, functions, and objects in certain parts of the runtime code. The scope determines the visibility of variables and other resources in the code block.

3. What is a closure?

Functions that can access variables inside other functions are called closures.
That kind of scene will be used, the encapsulation of some event functions.
The closure itself will bring resident memory, which will not be destroyed in time after being referenced.

4. Browser rendering process

When we enter a URL in the browser, a complete web page will eventually be presented. Will go through the following steps:

1. HTML loading

After entering the URL on the page, you will first get the HTML file. HTML is the basis of a page, so it will be downloaded at the very beginning, and it will be parsed after the download is complete

2. Downloading of other static resources
In the process of HTML parsing, if there are some external resource links in the HTML text, such as CSS, JS and pictures, etc., other threads will be enabled to download these static resources immediately. When a JS file is encountered in the head, the HTML parsing will stop. After the JS file is downloaded and executed, the HTML parsing work will continue to prevent JS from modifying the completed parsing results

From the above, it is known that JS files placed in the head belong to synchronous loading, which will block the construction of the DOM tree, thereby affecting the loading of the page. When there are many JS files, the time of the page white screen will also be longer

5. Introduction to data types:

The basic data types commonly used in js include undefined - - (undefined), null- - (empty), number - - (number), boolean- - (Boolean value), string- - (string), Symbol - - ( symbol);

The reference data type of js is the object type Object- - (object), such as: array - - (array), function - - (function), date - - (time), etc.;

6. Deep copy

Shallow copy: Shallow copy is to copy each attribute of the object in turn, but when the attribute value of the object is a reference type, what is actually copied is its reference, and when the value pointed to by the reference changes, it will also change

Deep copy: Deep copy and shallow copy are for complex data types (objects and arrays). Shallow copy only copies one layer, while deep copy is layer-by-layer copy. Deep copy copies the variable value. For non-basic type variables, it recurses to the basic type variable and then copies. The object after the deep copy is completely isolated from the original object and does not affect each other. Modifications to one object will not affect the other object.

7. Several methods of css horizontal centering

  1. Margin and width are realized, and a fixed width is defined on the container, and the value of left and right of the margin is auto.
  2. The content sets inline-block and the parent element text-align:center.
  3. Absolute positioning realizes horizontal centering. I think everyone is very familiar with it, and it must be used a lot.
  4. The flex implementation of css3.
  5. css3的fit-content 。

8. Do you know what practical higher-order functions are available for arrays?

There are many methods for arrays, all of which are simple and convenient, such as push, pop, etc., but there are many high-order functions used in practice. Now let’s summarize the methods and scenarios. First, what is a high-order function: high-order function , which is a function in which another function can be passed in as a parameter.
Click to view detailed case

  1. forEach
  2. filter
  3. map
  4. sort
  5. some
  6. every
  7. reduce
  8. find

9. The difference between call, apply, and bind

  • call, apply, and bind are the same : they all change the point of this, and the first parameter passed in is the point of binding this. In non-strict mode, if the first parameter is nul or undefined, the global object will be (The browser is window) As the value of this, it should be noted that in strict mode, null is null, and undefined is undefined
  • The only difference between call and apply is : call passes in a parameter list, and apply passes in an array, which can also be a class array
  • The difference between bind, call and apply : bind returns a function that changes the point of this, which is convenient for calling later, unlike call and apply, which will be called immediately; bind is similar to call, and the parameter list is also passed in, but it can be more Passing in once, no need like call, passing in once
  • It is worth noting : when the function returned by bind uses new as the constructor, the bound this value will be invalid, and this points to the instance object, but the incoming parameters are still valid (the priority of the new call > the bind call)

Vue category

10. The difference between vue2 and vue3

  1. The principle of two-way data binding is different
  2. Whether to support fragmentation;
  3. API types are different;
  4. Define data variables and methods are different;
  5. The lifecycle hook functions are different;
  6. The father and son pass parameters differently;
  7. Instructions are different from slots;
  8. The main.js file is different.

vue2: vue2 does not support fragments.
vue3: vue3 supports fragments (Fragments), that is to say, it can have multiple root nodes.
vue2: The two-way data binding of vue2 is realized by using an APIObject.definePropert() of ES5 to hijack the data, combined with the publish and subscribe mode.
vue3: ES6's Proxy API is used in vue3 to proxy data. Compared with vue2.x, the advantages of using proxy are as follows:
(1). defineProperty can only monitor a certain property, and cannot monitor all objects.
(2). It can save for in, closure and other content to improve efficiency (direct binding The entire object is enough)
(3). The array can be monitored, and there is no need to perform specific operations on the array alone. Vue3.x can detect changes in the internal data of the array.

11. The difference between route and router

router is an instance of VueRouter, which is equivalent to a global router object, which contains many attributes and sub-objects, such as history object. Frequently used jump links can use this.$router.push, which is the same as router-link jump.

route is equivalent to the current routing object. Some parameters can be obtained, and each route will have a router object, from which name, path, params, etc. can be obtained.

12. The difference between the two modes of vue routing

The hash mode
refers to the # sign and the following characters after the url. Every time the page is refreshed, it is directly changed after #.

Hash principle: flexible use of the aiming function of html, changing the path after # is essentially changing the aiming point of the current page, so the page will not be refreshed. Find the corresponding routing rules by listening to the browser's onhashchange() event change.

Since the change of the hash value will not cause the browser to send a request to the server, and the hash change will trigger the hashchange event (hashchange can only change the url fragment after #); although the hash path appears in the URL, it will not appear in the HTTP request. It has no effect on the backend at all, so changing the hash value will not reload the page, basically using hash to implement front-end routing.

The principle of history mode
history: Use two new APIs in H5's history: pushState() and replaceState() and an event onpopstate to monitor URL changes.

Contains back, forward, and go methods; the history mode URL must be consistent with the backend, so changing to history also requires the cooperation of the backend, otherwise an error will be reported; each refresh of history will re-request the entire URL to the backend, that is, re- request server. If the backend does not respond in time, an error 404 will be reported! .

13. The life cycle of keep-alive

During the component switching process, the switched components are kept in memory to prevent repeated rendering of the DOM, reduce loading time and performance consumption, and improve user experience

Components created in keep-alive will have two more lifecycle hooks: activated (used when the component is activated) and deactivated (called when the component leaves)

The trigger sequence of the hook is created->mounted->activated, and deactivated is triggered when exiting. When entering again (forward or backward), only activated is triggered

keep-ailve usage:

  • If you need to cache the entire project, just wrap router-view with keep-alive in app.vue
  • To cache some pages, you need to add a state in the meta attribute in the routing address configuration, and judge the router-view of the package in app.vue
  • You can also use exclude and include to specify which components are cached and which components are not cached

14. Advantages of mvvm:

  1. Both mvc and mvvm are a kind of design idea, mainly that the controller in mvc evolves into the viewModel in mvvm. Mvvm mainly solves the problem that a large number of dom operations in mvc improve page rendering performance and loading speed
  2. The biggest difference between mvvm and mvc is that it realizes the automatic synchronization of view and Model. When the properties of the model change, we don’t need to manually manipulate the dom element to change the display of the view, it will automatically change the dom
  3. On the whole, mvvm is much simpler than mvc, we don't need to use selectors to frequently operate dom

15. The role of virtual DOM

  • maintain the relationship between view and state
  • Improved rendering performance in complex view situations
  • Before updating the real DOM, the virtual DOM will use the Diff algorithm to compare the differences between the two new and old virtual DOM trees, realize partial updates, and finally update the differences to the real DOM

16. How does vue achieve performance optimization

1. Code modularization , commonly used places are encapsulated into separate components, referenced where needed, instead of writing too much repetitive code, each component must have a clear meaning, the higher the reusability, the better, and configurable The stronger the type, the better, including our css can also reduce repetitive code through custom css variables of less and sass.
2. The Vue route is set to lazy loading , which can speed up the rendering when the first screen is rendered.
3. Packaging optimization , modify the configuration items in vue.config.js, and set productionSourceMap to false, otherwise some map files will be generated after packaging. If not closed, the generation environment can view the source code through the map, and can Enable gzip compression to make the package smaller.
4. To reduce the use of pictures , you can use some css3 effects instead of picture effects, or use sprite images to reduce the size of pictures.
5. Import on demand , some third-party libraries we use can be loaded by importing on demand. Avoid introducing unnecessary parts and increase the project size for no reason
6. Use CDN to load some resources externally , such as vue-router, axios and other Vue peripheral plug-ins, set some unnecessary packaging in webpack.config.js and externals externally referenced module

17. Route Guard

Understanding of routing guards

There are three types of routing guards: global navigation guards, routing guards, and component navigation guards . Routing jump itself is a relatively complicated process, but this process can be refined through navigation guards, and corresponding operations can be performed in each refined process (hook function).

Route navigation guard : Navigation guard is some hook function before and after the route jump.
Route interception : before the route jumps to the specified path, you can manually jump to other routing interfaces, and you can also stop the jump .

Classification of routing guards
1 Global guards :

  • Global front guard: beforeEach will trigger multiple times,
  • Global resolution guard: beforeResolve resolution guard
  • Global post guard: afterEach passes the component instance object to the next callback of the component beforeRouteEnter guard

2. Routing guard :

  • Exclusive guard in beforeEnter route

3. Guards within the component :

  • beforeRouteEnter triggers before entering the component, and only triggers once when entering the component
  • beforeRouterUpdate Triggered before the component is updated (dynamic parameter change query string change) After entering the component, the parameter change can be triggered multiple times
  • beforeRouterLeave triggers before leaving the routing component and only triggers once when leaving the component

18. Why must the data in the Vue component be a function?

Because a component can be shared, but their data is private, each component must return a new data object, return a unique object, and do not share an object with other components.

If it is in object form, all instances will share the same data object. Once a component modifies data, all instances will be affected, which is an unwanted result.

In this way, the data attributes of each instance are independent and will not affect each other. So, you now know why the data of the vue component must be a function. This is all due to the characteristics of js itself, and has nothing to do with the design of vue itself.

19. What are the new features of ES6?

 - 新增了块级作用域(let,const)
 - 提供了定义类的语法糖(class)
 - 新增了一种基本数据类型(Symbol)
 - 新增了变量的解构赋值
 - 函数参数允许设置默认值,引入了rest参数,新增了箭头函数。
 - 数组新增了一些API,如isArray / from / of 方法;数组实例新增了 entries(),keys() 和 values() 等方法。
 - 对象和数组新增了扩展运算符
 - ES6新增了模块化(import / export)
 - ES6新增了Set和Map数据结构。
 - ES6原生提供Proxy构造函数,用来生成Proxy实例
 - ES6新增了生成器(Generator)和遍历器(Iterator) 

Talk about destructuring assignment

 - 解构:分解数据结构。
 - 赋值:为变量赋值。
 - 解构赋值:从数组或者对象中提取值,按照对应的位置,对变量赋值(在数组解构中,只 要解构的目标可以遍历,就可以实现解构赋值)。

20. The benefits of modular development:

  1. Avoid variable pollution, naming conflicts
  2. Improve code reuse
  3. Improved maintainability
  4. Easy dependency management

21. Disadvantages of JSON.stringify deep copy

1. If there is a time object in obj, the result of JSON.parse after JSON.stringify, time will only be in the form of a string, not in the form of an object. 2.
If there is a RegExp in obj, it will be printed out as an empty object.
3. If there is a function or undefined in the object, it will be discarded directly
4. If there is an object in json generated by a constructor, the constructon of the object will be discarded
5. If there is a circular reference in the object, deep copy cannot be implemented correctly
6 , if there is NAN in the object, it will become null after serialization

22. What is the difference between anti-shake and throttling?

During development, the following scenarios are often encountered: monitoring mouse movement onmousemove, monitoring page scrolling onscroll, monitoring size change onresize, monitoring input, button search, submit function, etc. In these scenarios, events will be triggered frequently, but we don't want events to be triggered frequently. In this case, we need to use anti-shake and throttling to limit frequent operations.

Both anti-shake and throttling are to solve the problem of frequent triggering of events, but there are some differences in implementation principles. See below for specific implementation principles.

1. Anti-shake (debounce):

When the anti-shake triggers a high-frequency event, it will only be executed once after n seconds. If it is triggered again within n seconds, it will be recalculated.

Brief summary: the previous delay call will be canceled every time it is triggered.

Application scenarios:
1. scroll event scrolling
2. zoom resize event of the browser window
3. when the search box enters a query
4. form validation
5. button submit event

code:

function debounce (fn, delay = 1000) {
    
    
  let time = null
  return function () {
    
    
    // 获取当前this
    let that = this
    // 判断是否已经存在,如果存在直接清除
    if (time) {
    
    
      clearTimeout(time)
    }
    time = setTimeout(() => {
    
    
      // 使fn 中this,执行当前调用者,并传入参数
      fn.apply(that, arguments)
    }, delay)
  }
}
// 测试demo
function logger(e){
    
    
	console.log('log -----')
}
btn.addEventListener('click',debounce(logger, 1000))

2. Throttle:

High-frequency event triggering, set a delayed call method each time an event is triggered, and cancel the previously delayed call method.

Brief summary: Every time an event is triggered, it will judge whether to wait for the delay function to be executed.

code:

function throttle (fn, delay = 1000) {
    
    
	let time = null;
	return function () {
    
    
		let that = this;
		// 如果已经存在定时器了,则 不做处理
		if (!time) {
    
    
			time = setTimeout(() => {
    
    
				fn.apply(that, arguments);
				// 完结时,将time改为null
				time = null;
			}, delay);
		}
	};
}

Difference: Reduce the frequency of callback execution and save computing resources.

  • The essence of anti-shake and throttling is different. Anti-shake is to turn multiple executions into the last execution, and throttling is to
    turn multiple executions into every other event execution
  • Events that must be triggered continuously by function anti-shake are only executed once at the end, while function throttling is only executed
    once within a period of time.

23. The role and use of promise objects in JS

Promise It is a new syntax proposed by ES6 to optimize the writing of asynchronous code.
The role of promise: ajax is an asynchronous request, multi-layer nesting will cause callback hell, promise simulates synchronization, and asynchronous callbacks are similar to synchronization to process business logic.

The promise's then method is an asynchronous method, but it will be executed prior to the timer.

1. The promise parameter is a function, and this callback function has two formal parameters (custom, generally written as resolve, reject) 2. The
promise has three states: pending (waiting), pending (success), rejected (failure), passed Parameters resolve, reject control
3. Once the state is sent and changed, it will not change again
4. Successfully execute the callback function in .then, and fail to execute the callback function in .catch

Features:

The asynchronous operation is expressed in the process of synchronous operation, avoiding layers of nested callback functions.
The process is clearer and the code is more elegant.
Promise objects provide a unified interface that makes it easier to control asynchronous operations.

shortcoming:

Promise cannot be canceled, it will be executed immediately once it is created, and cannot be canceled halfway.
If no callback function is set, errors thrown inside the Promise will not be reflected outside.
When it is in the pending state, it is impossible to know which stage it is currently progressing to (it has just started or is about to be completed).

24. async-await syntax

async,await is a new syntax in es7, which is used to further improve the writing of asynchronous code, and it is an upgraded version of promise!

async

  • The async function returns a Promise object.
  • The value returned by the return statement inside the async function is the value of the Promise object
function f1 () {
    
    
  return 1
}
async function f2 () {
    
    
  return 1
}
async function f3 () {
    
    }
const r1 = f1()
const r2 = f2()
const r3 = f3()
console.log(r1) // 1
console.log(r2) // Promise, resolved(1)
console.log(r3) // Promise, resolved(undefined)
r2.then(res => {
    
     console.log(res) })
r3.then(res => {
    
     console.log(res) })

await command

  • The outer function of await must have an async.
  • Under normal circumstances, the await command is followed by a Promise object, and the value of the promise is returned. If it is not a Promise object, return the corresponding value directly.

The execution flow inside the async function

  1. When executing an async function (named asyncF), enter the function:
  2. Execute synchronous code sequentially
  3. Encounter await, jump out of the asyncF function,
  4. Continue to execute subsequent code.
  5. After the execution of the asynchronous code after await is completed, the subsequent code in asyncF is executed.

25. Macrotasks and Microtasks

Why tasks are divided into synchronous tasks and asynchronous tasks

Just imagine, if the tasks of js are all synchronous, what will happen when you encounter tasks that need to be executed after a delay, such as timers and network requests?

The page may be paralyzed and needs to be paused to wait for the code that takes a long time to execute

Therefore, asynchronous tasks were introduced.

● Synchronous tasks: Synchronous tasks do not need to wait to see the execution results immediately, such as console
● Asynchronous tasks: Asynchronous tasks need to wait for a certain period of time to see the results, such as setTimeout, network requests

Asynchronous tasks can be subdivided into macro tasks and micro tasks. The following is a list of the macro tasks and micro tasks learned so far.
insert image description here
● Execute synchronous code first
● Encounter a macrotask, put it into the queue
● Encounter a microtask, put it into the microtask queue
● The execution stack is empty
○ Push the microtask into the stack for execution
● After all the microtasks are completed, take out the macrotask queue implement

Who executes macro tasks and micro tasks first ? Answer : Macro tasks

Guess you like

Origin blog.csdn.net/weixin_45449504/article/details/129140242