Summary of 2022 front-end interview questions (continuously updated~)

Table of contents

1. Anti-shake and throttling

2. js closure

Why is data in vue a function? (Frequent interview questions)

3. ES6 interview questions

3.1 The difference between var let const

3.2 Deconstruction 

3.3 How to use es6 to quickly deduplicate?

3.4 Promise interview questions What is the execution result of the following code?

4. Vue related

4.1 The difference between MVC and MVVM

4.2 Principle of v-model

4.3 Why is data in vue a function? (Frequent interview questions)

4.4 The difference between v-if and v-show

4.5 Why there is a key in v-for

5. Cross-domain solutions

5.1. Proxy in webpack

5.2. jsonp (requires backend support)

5.3. webpack plugin (plugin)

5.4. cors (backend solution)

6. git command

7. What is the difference between get and post requests

8. The difference between cookie, localStorage and sessionStorage 

9. The difference between async and await

10. The time of setTimeout is 0, and the cause of the error

11. Find the maximum value of an array?

12. Find the minimum value of an array?

13. Array deduplication 

14. Generate an array from 0 to the specified number 

15. Array sum

16. js data type

17. js variable hoisting

 18.This orientation

19. The difference between map and forEach

20. What is the difference between an arrow function and a normal function?

21. New in es6

22. Summary of array methods

23. Project performance optimization plan


1. Anti-shake and throttling

Anti-shake: After an event is triggered, the event is only executed once within n seconds. If the event is triggered again within n seconds, the execution time of the function will be recalculated.

For example, click the button, call the function after 2 seconds, and click again at 1.5 seconds, it will recalculate and call the function after 2 seconds.

Application scenario: pull down to the bottom to load the next page.

Throttling: Events that occur continuously within n seconds are only executed once

There are many application scenarios: search query

2. js closure

What is a closure: a closure is a function that can read variables inside other functions

function a() {

        let a1 = 1;

        return function() {

                return a1

        }

}

The significance of closure:

Can extend the life cycle of variables 4 can create a private environment

Closure benefits:

Can read internal variables of other functions

keep variables in memory

Can encapsulate private properties and methods of objects

Disadvantages: memory consumption, improper use will cause memory overflow problems

Why is data in vue a function? (Frequent interview questions)

The data in Vue must be a function, because when data is a function, the function will be called when the component is instantiated, and an object will be returned, and the computer will allocate a memory address to the object, and allocate several memory for several instantiations Addresses, their addresses are different, so the data in each component will not interfere with each other, changing the state of one of the components will not change the other components.

To put it simply, it is to ensure the independence and reusability of components. If data is a function, new data will be returned every time the component is reused, similar to creating a private data space for each component instance, protecting The respective data does not affect each other

3. ES6 interview questions

3.1 The difference between var let const

var: There is variable promotion; there is variable coverage, a variable that has been defined and assigned, if it is assigned again, the next value shall prevail; there is no block-level scope;

const: The definition is a constant, which must be assigned after the declaration; the defined value cannot be modified, otherwise an error will be reported; there is block-level scope; there is no variable promotion and variable coverage; the modification of elements of arrays and objects is not counted as constants Modify, no error will be reported.

let: has block-level scope; there is no variable promotion and variable coverage; let does not allow repeated declarations in the same scope, note that it is the same scope, and repeated declarations in different scopes will not report an error

3.2 Destructuring assignment 

let a = 1; let b = 2; If a=2, b=1 without declaring the third variable?

Answer: [a, b] = [b, a]

3.3 How to use es6 to quickly deduplicate?

let arr = [23, 12, 13, 33, 22, 12, 21]

let item = [...new Set(arr)]

3.4 Promise interview questions What is the execution result of the following code?

const promise = new Promise((resolve, reject) => {

        console.log(1)

        resolve()

        console.log(2)

})

promise.then(() => {

        console.log(3)

})

console.log(4)

Answer: 1,2,4,3

Explanation: The above investigation is about the principle of promise. The constructor of promise is executed synchronously. When the new promise is instant, 1 and 2 are executed immediately, while the .then method is executed asynchronously. When 1 and 2 are executed After that, output 4 will be executed, and finally output 3 will be executed

4. Vue related

4.1 The difference between MVC and MVVM

MVC: M (model data), V (view view), and C (controller controller). too dependent on the background

MVVM: M (model data), V (view view), VM (viewModel controls data changes and controls views) The
html part is equivalent to the View layer. You can see that the View here declaratively renders data into The DOM element, when the ViewModel updates the Model, is updated to the View through data binding. The data in the Vue instance is equivalent to the Model layer, and the core of the ViewModel layer is the two-way data binding in Vue, that is, the VIew can be updated in real time when the Model changes, and the View can also change the Model

The biggest difference between MVVM and MVC is that it realizes the automatic synchronization of View and Model, that is, when the properties of Model change, we no longer need to manually manipulate the Dom elements to change the display of View, but change the properties corresponding to View layer display will change automatically

4.2 Principle of v-model

It uses data hijacking combined with publisher-subscriber mode, hijacks the setter and getter of each property through Object.defineProperty(), publishes a message to the subscriber when the data changes, and triggers the corresponding monitoring callback to achieve data and view synchronization .

4.3 Why is data in vue a function? (Frequent interview questions)

In fact, it is a closure, because Vue is a single-page application, which is composed of many components, and each component has a data, so a private scope is created for each component through the closure, so that it will not interact with each other. Influence.

4.4 The difference between v-if and v-show

v-if is to show or hide by adding and removing elements

v-show modifies the display and hiding of elements by manipulating the DOM to modify the display style

If you need to display and hide elements frequently, use v-show for better performance

4.5 Why there is a key in v-for

key can improve the update efficiency of virtual DOM.

In Vue, the default "in-place multiplexing" strategy, when operating DOM, if there is no key, the options will be confused

key can only be a string or a number, other types are not allowed

1. The role of key in virtual DOM:

The key is the identifier of the virtual DOM object. When the data changes, Vue will generate a [new virtual DOM] according to the [new data], and then Vue will compare the difference between the [new virtual DOM] and the [old virtual DOM]. The comparison rules are as follows :

2. Comparison rules:

1) The old virtual DOM finds the same key as the new virtual DOM:

If the content in the virtual DOM has not changed, use the previous real DOM directly

If the content in the virtual DOM changes, a new real DOM is generated, and then the previous real DOM in the page is replaced

3. Possible problems caused by using index as key:

1) If the data is destroyed in the order of: adding in reverse order, deleting in reverse order, etc., there will be unnecessary real DOM updates ==> the interface effect is fine, but the efficiency is low

2) If the structure also contains the DOM of the input class, it will generate wrong DOM updates ==> there is a problem with the interface

4.6 The dist directory is too large after packaging, how to solve it?

1. There is a .map file in the file generated by dist packaging, which can be deleted. Configure in the vue.config.js file: productionSourceMap: false

2. Lazy loading, on-demand import, etc. are used for pricing and routing

3. Compress files and pictures. Install the compression component: compression-webpack-plugin

Import configuration after installation: 

Minimize code minisize: true

Split code: splitChunksl

Compress files that exceed the limit value, threshold: file size (in bytes)

4.7 The difference between watch and computed

The functions that can be completed by computed can be completed by watch

Small functions that can be completed by watch may not be completed by computed. For example: watch can perform asynchronous operations

Two important little principles:

1. All the functions managed by vue are best written as ordinary functions, so that the point of this is the vm or component instance object

2. For all functions not managed by Vue (timer callback, ajax callback, promise callback, etc.), it is best to write arrow functions, so that the point of this is the vm or component instance object

4.8 Data transfer between vue components

1. The parent component passes data to the child component

By binding custom properties to the subcomponent, and then using the props property in the subcomponent to receive it

2. The child component passes data to the parent component

1) The first way: through the parent component to pass the props of the function type to the child component: the child component passes data to the parent component

parent component:

 

 Subassembly:

 

2) The second way: Bind a custom event to the child component through the parent component: the child component passes data to the parent component

 parent component:

 

 Subassembly:

3) The third way: Bind a custom event to the child component through the parent component: use ref to achieve

 parent component:

 

 Subassembly:

 

3. Global event bus: can realize data transfer between any components 

main.js : Mount the global event bus to the Vue prototype so that all components can use it

 Sibling component A:

 Sibling component B:

4. Message subscription and publishing

A communication method between components, suitable for communication between any components.

Steps for usage:

1) Install pubsub: npm i pubsub-js

2) Import: import pubsub from 'pubsub-js'

3) Receive data: If component A wants to receive data, subscribe to the message in component A, and the subscribed callback stays in component A itself

mounted() {

        this.pid = punsub.subscribe('xxx', (data)=>{

                ......

        })

}

4) Provide data: pubsub.publish('xxx', data)

5) It is best to unsubscribe with pubsub.unsubscribe(pid) in the beforeDestory hook

5. Cross-domain solutions

Cross-domain: As long as the protocol, domain name and port number are different, cross-domain problems will occur. The same-origin policy is a security policy. The same origin refers to the same protocol, domain name, and port. For security reasons, the browser only allows interaction with interfaces under this domain name. Client scripts from different sources cannot read and write resources of the other party without explicit authorization.

Solution:

5.1. Proxy in webpack

devServer: {     proxy: { //Configure cross-domain       '/api': {         target: 'http://121.121.67.254:8185/', //The background address here is simulated; you should fill in your real background interface         changOrigin: true, //Used to control the post value in the request header,         pathRewrite is enabled by default: {           /* Rewrite the path, when we see the address of the request in the browser: http://localhost:8080/api/core/ The address actually accessed when getData/userInfo             is: http://121.121.67.254:8185/core/getData/userInfo, because /api            */           '^/api': ''          }       },     }   } is rewritten












5.2. jsonp (requires backend support)

Solution 1 *: wildcard, all allowed, there are security risks (not recommended).

Once this method is enabled, it means that any domain name can directly request across domains:
  1 server {   2 ...   3 location / {   4 # Allow all headers, all domains, all methods   5 add_header 'Access-Control-Allow-Origin' '*' ;   6 add_header 'Access-Control-Allow-Headers' '*';   7 add_header 'Access-Control-Allow-Methods' '*';   8 # OPTIONS directly return 204   9 if ($request_method = 'OPTIONS') {  10 return 204;  11 }  12 }  13 ...  14 }












Solution 2: Multi-domain name configuration (recommended)

Configure multiple domain names in the map and only allow cross-domain configurations:

  1 map $http_origin $corsHost {   2 default 0;   3 "~https://zzzmh.cn" https://zzzmh.cn;   4 "~https://chrome.zzzmh.cn" https://chrome.zzzmh .cn;   5 "~https://bz.zzzmh.cn" https://bz.zzzmh.cn;   6 }   7 server {   8 ...   9 location / {  10 # allow all headers all $corsHost domain all Method  11 add_header 'Access-Control-Allow-Origin' $corsHost;  12 add_header 'Access-Control-Allow-Headers' '*';  13 add_header 'Access-Control-Allow-Methods' '*';  14 # OPTIONS return directly 204  15 if ($request_method = ' OPTIONS') {














 16                 return 204;
 17             }
 18         }
 19         ...
 20     }

5.3. webpack plugin (plugin)

npm i -S webpack-dev-middleware installs the middle key and binds the front-end and back-end services together

middleware

let webpack = require('webpack')

let middle = require('webpack-dev-middleware')

let compiler = webpack(require('./webpack.config.js'))

app.use(middle(compiler))

5.4. cors (backend solution)

var allowCrossDomain = function(req,res,next) {

        // request source

        res.header("Access-Control-Allow-Origin", "*")

        // request header token

        res.header("Access-Control-Allow-Headers", "*")

        // request method get post put del

        res.header("Access-Control-Allow-Methods", "*")

        next();

}

app.use(allowCrossDomain )

6. git command

1. git init initializes the git warehouse (Command+Shift+. in mac can display hidden files)

2. git status View file status

3. git add file list track files

4. git commit -m commit information to submit the code to the warehouse

5. git log View submission records

6.1. Branch Details

(1) Master branch (master): A branch that is automatically generated when the update record is submitted to the git warehouse for the first time.

(2) Development branch (develop): As a development branch, it is created based on the master branch.

(3) Function branch (feature): as a branch for developing specific functions, it is created based on the development branch

6.2. Branch command

(1) git branch view branch

(2) git branch branch name to create a branch

(3) git checkout branch name switch branch

(4) git merge source branch to merge branches (note: the development branch must be merged on the master branch)

(5) git branch -d branch name to delete the branch (deletion is allowed only after the branch is merged) (-D force deletion)

6.3. Temporarily saving changes

(1) Store temporary changes: git stash

(2) Restore changes: git stash pop

7. What is the difference between get and post requests

Get is to get data from the server, and post is to send data to the server.

POST is more secure than GET because the data is not visible on the address bar.

The data submitted by the get method can only have a maximum of 1024 bytes, while the post does not have this limitation.

GET uses URL or Cookie to pass parameters. And POST puts the data in the request BODY.

Both GET and POST have their own semantics and cannot be mixed casually.

According to research, when the network environment is good, the difference between the time to send a packet and the time to send two packets is basically negligible. In the case of a poor network environment, TCP with two packets has a great advantage in verifying the integrity of the data packet. post is sent twice, get is sent only once.

8. The difference between cookie, localStorage and sessionStorage 

What they have in common: They are all saved on the browser side and have the same origin

difference:

Cookie data is always carried in the same-origin HTTP request (even if it is not required), that is, the cookie is passed back and forth between the browser and the server. Cookie data also has the concept of path (path), which can limit the cookie to only belong to a certain path. sessionStorage and localStorage will not automatically send the data to the server, but only save it locally.

The storage size limit is also different:

Cookie data cannot exceed 4K, sessionStorage and localStorage can reach 5M

sessionStorage: only valid until the current browser window is closed;

localStorage: always valid, the window or browser is closed and saved, local storage, so it is used as persistent data;

cookie: only valid until the set cookie expiration time, even if the window is closed or the browser is closed

different scope

sessionStorage: not shared in different browser windows, even on the same page;

localstorage: It is shared in all windows of the same origin; that is to say, as long as the browser is not closed, the data still exists

cookie: It is also shared in all windows of the same origin. That is to say, as long as the browser is not closed, the data still exists

9. The difference between async and await

the difference:

async is to define a function, define an asynchronous function, print the function name to get a promise object, the implication can be through this function name.then method

await is followed by any expression, generally using promise expression

async is internally implemented, and returns a value. Successfully returns promise.resolve(), and returns promise.reject() if an error occurs. The return value is captured by catch

await waits for the following promise object to be executed, and after getting the value of promise.resolve(), executes the following code. The expression after await can be promise.reject(), so it is recommended to put await in the try....catch statement

Advantages: async and await belong to es7 syntax. Easy to write, improve program efficiency, and avoid callback hell

Supplement: The difference between promise and async and await

Promise es6 syntax, promise contains catch, async needs to define catch by itself

Promise provides more methods, methods such as all and race are not available in aync.

10. The time of setTimeout is 0, and the cause of the error

setTimeout, if

If the time is 0, it will be inserted into the queue immediately, instead of executing immediately, waiting for the previous code to finish executing.

11. Find the maximum value of an array?

function getMaxArryNum(arr) {

        return Math.max(...arr)

getMaxArryNum([1,2,3,4,5,6])

12. Find the minimum value of an array?

const getMinArryNum= (arr) => {

        return Math.min(...arr)

getMinArryNum([1,2,3,4,5,6]) 

13. Array deduplication 

const removeEqual = (arr) => {

        const result = arr.filter((item, index, self) => {

                return self.indexof(item) === index

        })

        return result

removeEqual([1,2,3,4,5,6,1,2,3,42,1])

14. Generate an array from 0 to the specified number 

const getArr = (startNum, endNum) => {

        let arr = []

        for(var i=startNum; i<=endNum; i++){

                arr.push(i)

        }

        return arr

getArr(0, 4)

15. Array sum

const arrSum = (arr) => {

        const temp = arr.reduce((pre, now) => {

                return pre+now

        },0)

        return temp

}

arrSum([1,2,3,4])

16. js data type

js data types are divided into basic data types and complex data types

Basic data types: Boolean, Number, String, Null, Undefined

Complex data types: Object, Array, Function, Date

17. js variable hoisting

In js, variable and function declarations are hoisted to the top for execution

Function hoisting is higher than variable hoisting

If an external variable with the same name is declared with var inside the function, the function will no longer look up

Anonymous functions are not hoisted

 18.This orientation

this always refers to the direct caller of the function.

If there is a new keyword, this points to the new object

In the event, this points to the object that triggered the event

19. The difference between map and forEach

The forEach method is the most basic method, traversing and looping. There are 3 parameters by default: each element item traversed, the index index traversed, and the array array traversed

The map method is consistent with foreach, the difference is that it will return a new array, so the callback needs to have a return return value, if not, it will return undefined

20. What is the difference between an arrow function and a normal function?

The this object in the function body is the object where it is defined, not the object where it is used

It cannot be used as a constructor, that is to say, the new command cannot be used, otherwise an error will be reported

The arguments object cannot be used. This object does not exist in the function body. If you want to use it, you can use the Rest parameter instead

The yield command cannot be used, so arrow functions cannot be used as Generator functions

21. New in es6

Add template string

arrow function

Add let and const to declare variables

for-of is used to iterate over data - such as values ​​in an array

destructuring assignment

Added simple data type Symbol, which is unique and will not conflict with other attribute names

Incorporate Promise objects into the specification, providing native Promise objects

22. Summary of array methods

map loops through the array and returns a new array

forEach loops through the array without changing the original array

push/pop add/remove elements at the end of the array and change the original array

unshift/ shift Add/remove elements at the head of the array, changing the original array

join converts an array to a string

some returns true for one item, then the whole is true

Every item returns true, then the whole is false

filter array filtering

slice(start, end) Array interception, including the beginning, excluding interception, returns a new array

splice(start, number, value) delete array elements, change the original array

indexof/lastindexof: Find an array item and return the corresponding subscript

concat: array splicing, does not affect the original array, shallow copy

sort: Array sorting changes the original array

reverse: The array is reversed, changing the original array

23. Project performance optimization plan

Reduce http requests

Reduce DNS queries

use a CDN

avoid redirection

Image lazy loading

Routing lazy loading

Reduce DOM element manipulation

use external js and css

Compress js, css, fonts, pictures, etc.

Use iconfont font icons, sprite images, etc.

Avoid image src being empty

Put the stylesheet in the link

put js at the bottom of the page

Guess you like

Origin blog.csdn.net/Mr_LiuP/article/details/124078819