前端面试题汇总大全!

Front-end interview questions

文章目录


Summary of front-end interview questions (including super detailed answers) -- continuous update

1. HTML

1. What is the difference between xhtml and html

  • functionally
    • It is mainly XHTMLcompatible with major browsers, mobile phones PDA, and browsers can quickly and correctly compile web pages
  • writing habits
    • XHTMLElements must be properly nested, closed, and case-sensitive, and the document must have a root element

2. What are the inline elements? What are block-level elements? What are the empty (void) elements? What is the difference between inline elements and block level elements

Inline elements include: ab span img input select strong
Block-level elements include: div ul ol li dl dt dd h1 h2 h3 h4...p
Empty elements: br, hr img input link meta
Inline elements cannot set width and height, and do not occupy a single
block The width and height of level elements can be set, occupying a single line

3. Briefly describe your understanding of HTML semantics?

Semanticization refers to the selection of appropriate tags (code semantics) based on the structure of the content (content semantics)

Semantic benefits:

  • In the absence of CSS, the page can also present a good content structure
  • Semantics make the code more readable and facilitate team development and maintenance
  • Semantics are conducive to user experience (such as flexible use of title, label, and alt attributes)
  • Semantics is good for SEO (establishing good communication with search engines helps crawlers crawl more effective information. Crawlers rely on tags to determine the context and the weight of each keyword)

4. What is the difference between title and alt attributes on tags?

alt is for the search engine to identify, and the alternative text when the image cannot be displayed;
title is the annotation information about the element, mainly for users to interpret.
When the mouse is placed on the text or picture, the title text will be displayed. (Because IE is not standard) In the IE browser, alt plays the role of title and becomes a text prompt.
When defining the img object, write all the alt and title attributes to ensure that it can be used normally in various browsers.

5. What are the advantages and disadvantages of iframe?

advantage:

  • Addresses loading issues with slow-loading third-party content such as icons and ads
  • Security sandbox
  • Load scripts in parallel

shortcoming:

  • iframe will block the Onload event of the main page
  • Even if the content is empty, it will take time to load
  • no semantics
  • Problems with using iframe as a sub-application: 1. There are no records. 2. Severe style isolation

6. href and src?

  • href is the abbreviation of Hypertext Reference, which means hypertext reference. Used to establish a link between the current element and the document. Commonly used are: link, a
  • src is the abbreviation of source, and the content of src is an essential part of the page, which is the introduction. The content pointed to by src will be embedded in the document where the current tag is located. Commonly used are: img, script, iframe
  • The difference between href and src
    • 1. The types of requested resources are different: href points to the location of the network resource, and establishes a connection with the current element (anchor) or the current document (link). When the src resource is requested, the resources it points to will be downloaded and applied to the document, such as JavaScript scripts and img images;
    • 2. The results are different: src is used to replace the current element; href is used to establish a connection between the current document and the reference resource
    • 3. Browser parsing methods are different: when the browser parses to src, it will suspend the download and processing of other resources until the resource is loaded, compiled, and executed. The same is true for pictures and frames, similar to applying the pointed resource to current content. This is why it is recommended to put the js script at the bottom instead of the head.

7. What is progressive enhancement with graceful degradation?

Progressive Enhancement: Build pages for low-version browsers at the beginning, complete basic functions, and then perform effects, interactions, and additional functions for advanced browsers to achieve a better experience

Graceful Degradation: Build a fully functional site from the start, then test and fix against browsers. For example, at the beginning, an application was built using the features of CSS3, and then gradually hacked for major browsers so that it can be browsed normally on low-version browsers.

8. How many HTTP request methods are used?

  • GETmethod
    • Send a request to get a resource on the server
  • POSTmethod
    • URLSubmit data or append new data to the specified resource
  • PUTmethod
    • Similar to POSTthe method, it also submits data to the server. However, there are differences between them. PUTspecifies the location of the resource on the server, POSTwithout
  • HEADmethod
    • Only request the header of the page
  • DELETEmethod
    • Delete a resource on the server
  • OPTIONSmethod
    • It is used to get the currently URLsupported methods. If the request is successful, there will be a Allowheader containing “GET,POST”information like this
  • TRACEmethod
    • TRACEmethod is used to trigger a remote, application-level request message loop
  • CONNECTmethod
    • Convert the request connection to a transparent TCP/IPchannel

9. What are the HTTP status codes?

1. Temporary response

100——The client must continue to send requests
101——The client requires the server to convert the HTTP protocol version according to the request
2. Success

200——服务器成功返回网页
201——提示知道新文件的URL
202——接受和处理、但处理未完成
203——返回信息不确定或不完整
204——请求收到,但返回信息为空
205——服务器完成了请求,用户代理必须复位当前已经浏览过的文件
206——服务器已经完成了部分用户的GET请求
三、重定向

300——请求的资源可在多处得到
301——删除请求数据
302——在其他地址发现了请求数据
303——建议客户访问其他URL或访问方式
304——客户端已经执行了GET,但文件未变化
305——请求的资源必须从服务器指定的地址得到
306——前一版本HTTP中使用的代码,现行版本中不再使用
307——申明请求的资源临时性删除
四、请求错误

400—bad request, such as syntax error
401—request authorization failure
402—keep valid ChargeTo header response
403—request not allowed
404—the requested web page does not exist
405—the method defined by the user in the Request-Line field does not exist Allow
406—according to the Accept request sent by the user, the requested resource is not accessible
407—similar to 401, the user must first be authorized on the proxy server
408—the client did not complete the request within the time specified by the user
409—for the current Resource status, request cannot be completed
410 - The resource is no longer available on the server and there are no further references to the address
411 - The server rejected the request for the user-defined Content-Length attribute
412 - One or more request header fields are incorrect in the current request
413 - The requested resource is larger than the size allowed by the server
414 - The requested resource URL is longer than the length allowed by the server
415 - The requested resource does not support the requested item format
416 - The request contains the Range request header field, within the scope of the current requested resource There is no range indication value, and the request does not contain the If-Range request header field
417——The server does not meet the expected value specified in the Expect header field of the request. If it is a proxy server, it may be that the next-level server cannot satisfy the request.
5. Server error
500—— The server generates an internal error
501 - the server does not support the requested function
502 - the server is temporarily unavailable, sometimes to prevent system overload
503 - the server is timed out, overloaded or suspended for maintenance
504—the gateway is overloaded, the server uses another gateway or service to respond to the user, and the waiting time setting value is longer
505—the server does not support or refuses to support the HTTP version specified in the request header

10. What is the function of DOCTYPE (document type)?

DOCTYPE is a document type declaration of a standard universal markup language in HTML5. Its purpose is to tell the browser (parser) what kind of document type definition (html or xhtml) should be used to parse the document. Different rendering modes will affect browsing. parser for CSS code and even JavaScript scripts. It must be declared on the first line of the HTML document.

There are two modes in which the browser renders the page:

  • CSS1Compat: Standard mode (Strick mode), the default mode, the browser uses the W3C standard to parse and render the page. In standards mode, the browser renders pages in the highest standard it supports.
  • BackCompat: Weird mode (mixed mode) (Quick mode), the browser uses its own weird mode to parse and render the page. In quirks mode, pages are displayed in a more relaxed backwards-compatible way.

11. What SEOs should be paid attention to on the front end?

  • Reasonable title, description, keywords: search engines reduce the weight of this item one by one, the title value can only emphasize the key points, important keywords should not appear more than 2 times, and should be placed in the front, different page titles should be different; description Highly summarize the content of the page, the length is appropriate, do not pile up keywords too much, the description of different pages is different; keywords just list important keywords
  • Semantic HTML code, in line with W3C specification: Semantic code makes it easy for search engines to understand web pages
  • HTML codes for important content are placed first: search engines crawl HTML from top to bottom, and some search engines have restrictions on the length of crawling to ensure that important content will be crawled
  • Do not use js output for important content: crawlers will not execute js to obtain content
  • Use less iframes: Search engines won't crawl content inside iframes
  • Non-decorative pictures must add alt
  • Improve site speed: Site speed is an important indicator of search engine ranking

12. What is the difference between defer and async in the script tag?

Note: If there is no defer or async attribute, the browser will load and execute the corresponding script immediately. It will not wait for subsequent loaded document elements, it will start loading and executing when it is read, thus blocking the loading of subsequent documents.

the difference:

  • Execution order: Multiple tags with async attributes cannot guarantee the order of loading. Multiple tags with defer attributes will be executed in the order of loading
  • Whether the script is parallel: asyncattribute, indicating that the loading and execution of the subsequent document and the loading and execution of the js script are carried out in parallel 文档加载与js加载同时进行. deferAttribute, the js script needs to wait for all elements of the document to be parsed before executing, before the DOMContentLoaded event is triggered.

13. What are the commonly used meta tags?

metaLabels are defined by nameand contentattributes for描述网页文档的属性

Commonly used meta tags:

  • charset: used to describe the encoding type of the HTML document
  • keywords: page keywords
  • description:page description
  • refresh: page redirection and refresh
  • viewport: Adapt to the mobile terminal, you can control the size and ratio of the viewport
    • content parameter details:
      • width viewport: width (value/device-width)
      • height viewport: height (value/device-height)
      • initial-scale: initial zoom ratio
      • maximum-scale: maximum zoom ratio
      • minimum-scale: minimum zoom ratio
      • user-scalable: Whether to allow users to zoom (yes/no)

14. What is the process of a complete HTTP transaction?

  • Enter the URL in the browser's address bar and press Enter.
  • The browser checks whether there is a cache for the current URL, and compares whether the cache is expired.
  • DNS resolves the IP corresponding to the URL.
  • Establish a TCP connection (three-way handshake) based on IP.
  • HTTP initiates a request.
  • The server processes the request and the browser receives the HTTP response.
  • Render the page and build the DOM tree.
  • Close the TCP connection (four waves).

15. What is the difference between HTTP and HTTPS?

http: Hypertext Transfer Protocol, which is a client-side and server-side request and response standard (TCP), is used to transfer hypertext from the www server to the local browser. It can make the browser more efficient and reduce network transmission.

https: It can be understood as a secure version of http, adding an SSL layer under http. The main function of the https protocol is to establish a secure information channel to ensure the transmission of the array and ensure the authenticity of the website.

the difference:

  • The Https protocol requires a ca certificate, which costs a lot.
  • http is the hypertext transfer protocol, and the information is transmitted in plain text, while https is the secure ssl encrypted transfer protocol.
  • Different connection methods have different ports. Generally speaking, the port of http protocol is 80, and the port of https is 443.
  • The http connection is very simple and stateless; the HTTPS protocol is a
    network protocol constructed by the SSL+HTTP protocol that can perform encrypted transmission and identity authentication, and is safer than the http protocol.

16. How does HTTPS implement encryption?

HTTPS requires a handshake between the client (browser) and the server (website) before transmitting data. During the handshake, the password information for encrypted data transmission between the two parties will be established. The TLS/SSL protocol is not only a protocol for encrypted transmission, but also a work of art carefully designed by the artist. Asymmetric encryption, symmetric encryption and HASH algorithm are used in TLS/SSL

17. What is the role of the srcset attribute of img? img loads different images

Different images are often used in responsive pages according to the screen density. At this time, the srcset attribute of the img tag is used. The srcset attribute is used to set different screen densities, and the image loaded by img is different.

18.What are WEB standards and W3C standards?

  • Label closure, label lowercase, no random nesting, use of external links cssand jsseparation of structural behavior

19. How to use offline storage of HTML5? working principle?

Offline storage refers to: when the user is not connected to the Internet, the site or application can be accessed normally, and when the user is connected to the Internet, the cache file on the user's machine is updated.

Principle : The offline storage of HTML5 is based on a newly created .appcache file caching mechanism (not a storage technology). Resources are stored offline through the parsing list on this file, and these resources will be stored like cookies. Later, when the network is offline, the browser will display the page through the data stored offline.

How to use :

  • Create a manifest file with the same name as html, and then add the manifest attribute to the head of the page
  • 在cache .manifest文件中编写需要离线存储的资源
    • CACHE:表示需要离线存储的资源列表,由于包含 manifest 文件的页面将被自动离线存储,所以不需要把页面自身也列出来。
    • NETWORK:表示在它下面列出来的资源只有在在线的情况下才能访问,他们不会被离线存储,所以在离线情况下无法使用这些资源。不过,如果在 CACHE 和 NETWORK
      中有一个相同的资源,那么这个资源还是会被离线存储,也就是说 CACHE 的优先级更高
    • FALLBACK:表示如果访问第一个资源失败,那么就使用第二个资源来替换他,比如上面这个文件表示的就是如果访根目录下任何一个资源失败了,那么就去访问
      offline.html
  • 在离线状态时,操作window.applicationCache进行离线缓存的操作。

20.浏览器是怎么对HTML5的离线储存资源进行管理和加载的呢?

  • 在线的情况下,浏览器发现html头部有manifest属性,它会请求manifest文件,如果是第一次访问app,那么浏览器就会根据manifest文件的内容下载相应的资源并且进行离线存储。如果已经访问过app并且资源已经离线存储了,那么浏览器就会使用离线的资源加载页面,然后浏览器会对比新的manifest文件与旧的manifest文件,如果文件没有发生改变,就不做任何操作,如果文件改变了,那么就会重新下载文件中的资源并进行离线存储。
  • 离线的情况下,浏览器就直接使用离线存储的资源。

21.label的作用是什么?

label标签来定义表单控件的关系: 当用户选择label标签时,浏览器会自动将焦点转到和label标签相关的表单控件上

22.Canvas和SVG区别?

Canvas : Canvas, which draws 2D graphics through Javascript, and dyes them pixel by pixel. When its position changes, it will be redrawn.

SVG : 矢量图形Scalable Ecor Grdhics) is a language for 2D graphics based on Extensible Markup Language XML. The fact that SVG is based on XML means that all elements in the SG DOM are available, and a Javascript event handler can be attached to an element. In SVG, each drawn shape is considered an object. Browsers can automatically reproduce graphics if the properties of the SVG object change.

the difference:

  • Each graphic element drawn by svg is an independent DOM node. SVG is based on XML, which means that every element in the SVG DOM is available. You can attach a Javascript event handler to an element, which can be easily bound Event or used to modify. The output of canvas is a whole canvas
  • The graphics output by svg are vector graphics, and the parameters can be modified later to zoom in and out freely without jaggedness. And canvas outputs a scalar canvas, just like a picture, zooming in will be distorted or jagged

23. What is the function of the head tag, and which tag is essential?

The tag is used to define the head of the document, which is the container for all head elements. The meta in can refer to scripts, instruct the browser where to find stylesheets, provide meta information, and more. The following tags can be used in the head section: ,,,

24. How does strict mode differ from promiscuous mode? What do they mean?

Strict mode : also known as standard mode, means that the browser parses the code according to the w3C standard;

Promiscuous mode : Also known as weird mode and compatibility mode, it means that the browser parses the code in its own way. Promiscuous mode usually mimics the behavior of older browsers to prevent older sites from working;

distinguish:

  • If the document contains a strict DOCTYPE, it is generally rendered in strict mode (strict DTD—strict mode)
  • A DOCTYPE that contains a transitional DTD and a URI, also renders in strict mode, but having a transitional DTD without a URI
    (Uniform Resource Identifier, which is the address at the end of the declaration) causes the page to render in promiscuous mode (
    transitional DTD with URI -- strict mode ; Transitional DTD without URI -- promiscuous mode)
  • The non-existence or incorrect form of DOCTYPE will cause the document to be rendered in mixed mode (DTD does not exist or is incorrectly formatted—mixed mode);
  • HTML5 has no DTD, so there is no difference between strict mode and mixed mode, and backward compatibility has been achieved as much as possible (HTML5 has no distinction between strict and mixed).

25. What is the reason for the garbled characters in the browser? How to solve?

Causes of garbled characters :

  • The source code of the webpage is encoded by gbk, and the Chinese characters in the content are encoded by utf-8. In this way, HTML garbled characters will appear when the browser is opened, and garbled characters will also appear on the contrary:
  • The encoding of the html web page is gbk, and the program calls out the content of utf-8 encoding from the database, which will also cause garbled encoding;
  • The browser cannot automatically detect the encoding of the web page, resulting in garbled characters on the web page.

Solution :

  • Use software to edit HTML web content;
  • If the web page setting encoding is gbk, and the encoding format of the database storage data is UTF-8, at this time, the program needs to query the database data and display the data forward program transcoding:
  • If there are garbled characters on the webpage when browsing in the browser, find the conversion code menu in the browser to convert.

26. Browser storage technology?

Cookie : It is a technology that can be stored locally in the browser for the session between the client and the server. It can store 4kb data, and the purpose is to identify the user's identity

LocalStorage : Added in HTML5 for use as local storage, which solves the problem of insufficient storage space for cookies (the storage space for each cookie in a cookie is 4k)

SessionStorage : The only difference between sessionStorage and localStorage is that localStorage belongs to permanent storage, while sessionStorage belongs to When the session ends, the key-value pairs in sessionStorage will be cleared.

27. How to optimize images? Difference in image format?

1. Do not use pictures, try to use css3 instead. For example, to achieve modification effects, such as translucency, borders, rounded corners, shadows, gradients, etc., CSS can be used in current mainstream browsers.

2. Use vector graphics SVG instead of bitmaps. For most patterns, icons, etc., vector graphics are smaller and scalable without generating multiple sets of plots. All major browsers now support SVG, so you can use it with confidence!

3. Use the appropriate image format. Our common image formats are JPEG, GIF, and PNG; lossless compressed PNG is usually more suitable for retouching images.

GIFs basically don't use anything but animated GIFs. And for animation, it is recommended to use video elements and video formats, or use SVG animation instead.

4. Set a reasonable cache according to the HTTP protocol.

5. Use font icon webfont, CSS Sprites, etc.

6. Implement preloading with CSS or JavaScript.

7. WebP picture format can bring optimization to the front end. WebP supports lossless and lossy compression, dynamic and static pictures, and the compression ratio is better than GIF, JPEG, JPEG2000, PG and other formats, which is very suitable for network and other picture transmission

Picture format difference:

  • gif: is a lossless, 8-bit image format. It supports animation, index transparency, compression and other features. It is suitable for pictures with simple colors (less tones), such as logos, various small icons, etc.
  • The JPEG format is a compressed image format that balances size and quality. It is suitable for photos with rich colors that allow slight distortion, and it is not suitable for pictures with simple colors (less tones), such as logos, various small icons, etc.
  • PNG: PNG can be subdivided into three formats: PNG8, PNG24, PNG32. The following number represents the maximum color value that this PNG format can index and store.
    Regarding transparency: PNG8 supports index transparency and alpha transparency; PNG24 does not support transparency; and PNG32 adds 8-bit (256-order) alpha channel transparency to 24-bit PNG;

28. Write as many browser compatibility issues as possible? solve

  • The default margin and padding of labels in different browsers are different
    • At the beginning of the CSS file, add *{margin: 0; padding: 0;} to set the margin and padding of all tags to 0
  • After the block attribute tag is float, and there is a horizontal margin, IE6 shows that the margin is larger than the setting
    • Block-level element display can be set to inline
  • Set a small height label (generally less than 10px), in IE6, IE7, the actual height will exceed the set height, because the browser sets a default minimum height for the label
    • Set {overflow: hidden;}, or set the line-height to be smaller than the height you set.
  • In some browsers, images have default spacing (all labels with text attributes will have margins, unless two labels are connected together without separation);
    • Use float for img layout, because all tags will become block-level elements after setting float, and block-level elements will be close together when floating, without margins
  • Browsers below IE9 cannot use opacity;
  • {opacity: 0.5;filter: alpha(opacity = 50);filter: progid:DXImageTransform.Microsoft.Alpha(style = 0, opacity = 50);}。

29. What are the global attributes of HTML?

  • class: Set the class identifier for the element
  • data-*: Add a custom attribute to the element
  • draggable: Set whether the element is draggable
  • id: element id, unique within the document
  • lang: language of element content
  • style: inline cssstyle
  • title: Advice information related to the element

30. What is the webpage verification code for, and what security problem is it to solve?

  • A public fully automatic program that distinguishes whether the user is a computer or a human. It can prevent malicious cracking of passwords, swiping tickets, and flooding forums
  • Effectively prevent hackers from making continuous login attempts to a specific registered user with a specific program brute force cracking method

31. Why is it more effective to use multiple domain names to store website resources?

  • CDNCaching is more convenient
  • Breakthrough browser concurrency limit
  • save cookiebandwidth
  • Save the number of connections of the main domain name and optimize page response speed
  • Prevent unnecessary security issues

32. There are a lot of pictures on a page (large e-commerce website), and the loading is very slow. What methods do you have to optimize the loading of these pictures to give users a better experience.

  • Lazy loading of pictures, you can add a scroll event to the unvisible area on the page to judge the distance between the position of the picture and the top of the browser and the distance from the page, if the former is smaller than the latter, it will be loaded first.
  • If it is a slideshow, photo album, etc., you can use the image preloading technology to download the previous and next images of the currently displayed image first.
  • If the picture is a css picture, you can use CSSsprite, SVGsprite, Iconfont, Base64and other techniques.
  • If the picture is too large, you can use a specially encoded picture. When loading, a particularly compressed thumbnail will be loaded first to improve the user experience.
  • If the image display area is smaller than the real size of the image, the image is compressed first on the server side according to business needs, and the size of the image after compression is the same as that displayed.

33. What are the methods of session tracking in web development

  • cookie
  • session
  • urlrewrite
  • hideinput
  • ipaddress

34. The difference between title and h1, the difference between b and strong, the difference between i and em

  • titleThe attribute has no clear meaning and only indicates a title, while H1 indicates a title with a clear hierarchy, which also has a great impact on the crawling of page information
  • strongIt is to indicate the key content, and it has the meaning of strengthening the tone. When using a reading device to read the Internet: 会重读,而it is to display the emphasized content
  • i content is displayed in italics, em means emphasized text

35. What are the cores of browsers? What are the respective browsers?

  • IE: tridentkernel
  • Firefox: geckokernel
  • Safari: webkitkernel
  • Opera: It used to be prestothe kernel, Operabut it has been changed to Google Chrome- Blinkkernel
  • Chrome:Blink(Based on webkit, co-developed by Google and Opera Software)

36. How does the browser render the page?

  • 1. Parse the document to build the DOM tree
  • HTML/XHTML/SVG: After parsing these three files, a DOM tree will be generated (DOM Tree)
  • CSS: parse the style sheet and generate a CSS rule tree (CSS Rule Tree)
  • JavaScript: Parse scripts, operate DOM Tree and CSS Rule Tree through DOM API and CSSOM API, and interact with users.
  • 2. Build the rendering tree
  • After parsing the document, the browser engine will attach the CSS Rule Tree to the DOM Tree, and construct the Rendering Tree (rendering tree) based on the DOM Tree and the CSS Rule Tree
  • 3. Layout and draw rendering tree
  • Parse position, overflow, z-index and other attributes, and calculate the position and size of each rendering tree node. This process is called reflow. Finally, the Native GUI API of the operating system is called to complete the drawing (repain).

37. Why does TCP need three-way handshake and four-way handshake

The three-way handshake is to establish a reliable data transmission channel, and the four-way handshake is to ensure that the connection is closed after the data is received.

38. TCP three-way handshake

  • When a client needs to establish a connection, it will send a message to confirm the connection. This message is a synchronous message SYN = 1, and a random sequence number seq = x will be generated. This is the first handshake
  • When the server receives the connection request message, it will send a synchronization message confirmation message, this message SYN = 1, and ACK = 1, and the server will also randomly generate a seq = y, and set the ack Into x + 1, back to the client, this is the second handshake
  • When the client receives the ACK message from the server, it will reply with an ACK confirmation message to confirm that the confirmation message has been received. This message ACK = 1, seq = x + 1, ack = y + 1, which means is the third handshake;
  • Here is a point to explain: the uppercase ACK indicates that the type of the message is a confirmation message, and the lowercase ack is the confirmation number in the message. This confirmation number is obtained by adding 1 to the seq value of the other party in the last handshake.

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-bU41OHCQ-1686967105034)(file:///C:\Users\lenovo\AppData\Local\Temp\ksohtml7300 \wps2.jpg)]

39.TCP waved four times

  • The client initiates a FIN disconnection message, carrying a randomly generated seq value u, and sends it to the server, and it is in the FIN-WSIT state. This is the first wave;
  • After receiving the FIN message, the server replies with a confirmation message, where ACK = 1, randomly generates a seq, and ack = u + 1, which is the second wave;
  • When the server has finished sending the data, it sends a FIN message to the client to notify the client that the server is ready to close the connection. This message is FIN = 1, ACK = 1, ack = u + 1, seq = w, This is the third wave;
  • When the client receives the FIN confirmation message, it sends another FIN confirmation message, where ACK = 1, seq = u + 1, ack = w + 1, and enters the TIME-WAIT state, and closes the connection after waiting for 2MSL. This is the fourth wave.

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-oh7C8Oyl-1686967105036)(file:///C:\Users\lenovo\AppData\Local\Temp\ksohtml7300 \wps3.jpg)]

40. What is the role of data-attribute?

data-is a new addition to H5 to provide custom attributes for front-end developers.
These attribute sets can be obtained through the dataset attribute of the object.
Browsers that do not support this attribute can obtain it through the getAttribute method:
it should be noted that: after data- Attributes consisting of multiple words separated by hyphens are obtained in camel case. All major browsers support data-* attributes.
That is: when there are no suitable attributes and elements, the custom data attribute is able to store the private custom data of the page or App

41. New features of HTML5?

1.语义化标签

  • header: defines the header of the document (header)

  • nav: the section that defines the navigation links

  • footer: defines the footer (bottom) of the document or section

  • article: defines the content of the article

  • section: defines the section in the document (section, section)

  • aside: defines the content outside of the content it is on (side)

2.媒体标签

  • audio: audio
    • Attributes:
      • src audio link
      • controls control panel
      • autoplay
      • loop='true' loop playback
  • video: video
    • Attributes:
      • poster: The specified video has not been fully downloaded, or the user has not clicked on the cover that is displayed before playing. By default, the first stitch of the current video file is displayed, of course, you can also specify it yourself through the poster
      • controls: control panel
      • width,height
  • source tag: Because browsers support different video formats, in order to be compatible with different browsers, you can specify the video source through source.

3.表单

  • Form type:
    • email: It can verify whether the currently entered email address is legal
    • url : verification URL
    • number: Only numbers can be entered, other input is not allowed, and it has its own up and down arrows for increasing and decreasing. The max attribute can be set to the maximum value, min can be set to the minimum value, and value is the default value.
    • search : A small fork will be provided behind the input box, which can delete the input content, which is more humanized.
    • range : 可以提供给一个范围,其中可以设置max和min以及value,其中
      value属性可以设置为默认值
    • color : 提供了一个颜色拾取器
    • time : 时分秒
    • date : 日期选择年月日
    • datatime: 时间和日期(目前只有Safari支持)
    • datatime-local: 日期时间控件
    • week : 周控件
    • month: 月控件
  • 表单属性:
    • placeholder: 提示信息
    • autofocus : 自动获取焦点
    • autocomplete=“on” 或者 autocomplete=“off”使用这个属性需要有两个前提:
      • 表单必须提交过
      • 必须有name属性
    • required: 要求输入框不能为空,必须有值才能够提交
    • pattern=””里面写入想要的正则模式
    • multiple: 可以选择多个文件或者多个邮箱
    • form=form表单的ID!
  • 表单事件:
    • oninput 每当input里的输入框内容发生变化都会触发此事件。
    • oninvalid 当验证不通过时触发此事件。

4.进度条,度量器

  • progress标签:用来表示任务的进度 (IE、Safari不支持) ,max用来表示任务的进度,value表示已完成多少
  • meter属性: 用来显示剩余容量或剩余库存 (IE、Safari不支持)
    • high/low:规定被视作高/低的范围
    • max/min: 规定最大/小值
    • value: 规定当前度量值

5.DOM查询操作

  • document.querySelector()
  • document.querySelectorAll()

6.Web存储

  • localStorage和sessionStorage

7.其他

  • 拖放:拖放是一种常见的特性,即抓取对象以后拖到另一个位置。设置元素可拖放
  • canvas和svg
  • websocket,webwork
  • 地理定位
  • data-自定义属性

42.web worker的理解?如何创建?

In an HTML page, if the state of the page is not responsive when the script is executed, the page does not become responsive until the script is executed. A web worker is a js running in the background, independent of other scripts, and will not affect the performance of the page. And pass the result back to the main thread through postMessage. In this way, when performing complex operations, the main thread will not be blocked.

create:

  • Detect browser support for web workers
  • Create web worker files (js, callback functions, etc.)
  • Create a web worker object

43. Talk about HTML5 drag API

dragstart: The main body of the event is the dragged and dropped element, which is triggered when the dragged and dropped element starts to be dragged and dropped.
darg: The event body is the dragged and dropped element, which is triggered when the dragged and dropped element is being dragged and dropped.
dragenter: The event body is the target element, which is triggered when the dragged element enters an element.
dragover: The event body is the target element, which is triggered when it is dragged and moved within an element.
dragleave: The event body is the target element, and is triggered when the dragged element moves out of the target element.
drop: The event body is the target element, which is triggered when the target element fully accepts the dragged and dropped element.
dragend: The event body is the element being dragged and dropped, which is triggered when the entire drag and drop operation ends.

44. Http short polling, long polling

Polling: The client sends an HTTP request to the server at regular intervals (for example, every 5s), and the server returns the latest data to the client after receiving the request.

Client polling: short polling, long polling

  • Short polling: Generally, the client initiates an ordinary HTTP request to the server at intervals (eg, every 5s). The server queries whether there is data update on the current interface. If there is data update, it will return the latest data to the client. If not, it will prompt the client that there is no data update.
  • Long polling: Generally, the client sends an HTTP request with a longer network timeout to the server, and does not actively disconnect the connection before the Http connection times out; after the client times out or returns data, another one is established The same Http request, repeat the above process

45. Canvas drawing basics (line, triangle, rectangle, circle)

<canvas id=“myCanvas” width=200 height=100 ></canvas>
  • id 是canvas元素的标识;
  • height,width规定画布大小

直线

beginPath()方法,指示开始绘图路径: ctx.beginPath();
moveTo()方法将坐标移至直线起点: ctx.moveTo(x,y);
lineTo()方法绘制直线: ctx.lineTo(x,y);
stroke()方法,绘制图形的边界轮廓: ctx.stroke();
closePath()方法,指示闭合绘图路径: ctx.closePath()

    var mycanvas=document.getElementById("canvas");
    var ctx=mycanvas.getContext("2d");
	ctx.beginPath();
	ctx.moveTo(100,100);//移动到绘制点
	ctx.lineTo(200,200);
	ctx.strokeStyle="#000000"; //指定描边颜色
	ctx.stroke();

三角形

	var mycanvas=document.getElementById("canvas");
    var ctx=mycanvas.getContext("2d");
	ctx.beginPath();
	ctx.moveTo(100,200);
	ctx.lineTo(400,200);
	ctx.lineTo(250,400);
	ctx.closePath();//闭合绘图
	ctx.strokeStyle="#000000";
	ctx.stroke();

矩形

绘制矩形:rect(x,y,width,height);

绘制矩形边框:strokeRect(x, y, width, height);

绘制填充矩形:fillRect(x, y, width, height);

擦除指定矩形区域:clearRect(x, y, width, height);

	var mycanvas=document.getElementById("canvas");
	var ctx=mycanvas.getContext("2d");
 
	//rect()函数调用
	ctx.beginPath();
	ctx.rect(20,20,100,50);
	ctx.stroke();

圆形:arc(centerx,centery,radius,startAngle,endAngle,antiClockwise);

  • centerx,centery 圆弧中心点坐标
  • Radius 半径
  • startAngle 起始弧度
  • endAngle 终止弧度
  • antiClockwise 是否按逆时针方向绘图, 是一个可选参数,默认为false(即顺时针方向绘图)
    弧度 = 角度* ( Math.PI / 180 )
	var mycanvas=document.getElementById("canvas");
	var ctx=mycanvas.getContext("2d");
	//arc()函数调用
	ctx.beginPath();
	ctx.arc(100,150,70,0,90*Math.PI/180,true);
	ctx.stroke();

46.TCP和HTTP区别?

  • TCP对应于传输层,HTTP对应于应用层,从本质上来说,二者没有可比性。

  • Http协议是建立在TCP协议基础之上的,当浏览器需要从服务器获取网页数据的时候,会发出一次Http请求。Http会通过TCP建立起一个到服务器的连接通道,当本次请求需要的数据完毕后,Http会立即将TCP连接断开,这个过程是很短的。所以Http连接是一种短连接,是一种无状态的连接

  • TCP is the underlying protocol, which defines the specification of data transmission and connection methods.

    HTTP is an application layer protocol, which defines the specification of the content of the transmitted data.

    The data in the HTTP protocol is transmitted using the TCP protocol, so supporting HTTP must support TCP

2. CSS articles

1. Introduce the box model of CSS?

margin (outer margin) - Clear the area outside the border, the margin is transparent.
border - A border around the padding and outside the content.
padding - Clears the area around the content, the padding is transparent.
content (content) - the content of the box, display text and images.

W3C's standard box model: In the standard box model, width refers to the width of the content part

IE's box model: In the IE box model, width represents the width of the three parts of content+padding+border

  • How to enable different box models
    • box-sizing:content-box; standard box model
    • box-sizing: border-box; IE box model

2. css selector?

  • id selector (#box), select the element whose id is box
  • Class selector (.one), selects all elements with the class name one
  • Label selector (div), select all elements with label div
  • Descendant selector (#box div), selects all div elements with id inside the box element
  • Child selector (.one>one_1), selects all elements of .one_1 whose parent element is .one
  • Adjacent sibling selector (.one+.two), selects all .two elements immediately after .one
  • Group selector (div, p), select all elements of div, p
  • pseudo class selector
  • attribute selector

3. css selector priority?

!important > inline style (weight 1000) > ID selector (weight 100) > class selector (weight 10) > label (weight 1) > wildcard > inheritance > browser default attribute

4. Inheritable attributes in css?

  • font family attribute
    • font-family: font family
    • font-weight: font weight
    • font-size: font size
    • font-style: font style
  • Text Series Properties
    • text-indent: text indentation
    • text-align: horizontal alignment of the text
    • line-height: row height
    • color: text color
  • Element visibility: visibility
  • List layout attribute: list-style
  • Cursor property: cursor

5. How many ways to center vertically?

  • Set the display mode to table, display:table-cell, and setvertial-align:middle
  • Using flexlayout, set toalign-item:center
  • Set in absolute positioning bottom:0,top:0, and setmargin:auto
  • When the height is fixed in absolute positioning, the setting top:50%,margin-topvalue is a negative value of half the height
  • text vertical center set line-heightto heightvalue

6. Briefly explain the difference and usage between CSS link and @import?

  • link is an XHTML tag, in addition to loading CSS, it can also be used to define RSS, define rel connection attributes, etc.; while @import is provided by CSS and can only be used to load CSS;
  • When the page is loaded, the link will be loaded at the same time, and the CSS referenced by @import will wait until the page is loaded before loading;
  • import is proposed by CSS2.1, and can only be recognized by IE5 and above, and link is an XHTML tag, so there is no compatibility problem

7. What is the difference between the transparency effects of rgba and opacity?

  • Rgba can specify both the element color and the transparency, opacity can only control the transparency of the element and cannot set the color
  • Rgba transparency is based on the actual color and opacity is set for the transparency of the element itself. Using rgba can achieve different transparency in different parts of the element, while opacity makes the transparency of the element consistent
  • Browsers that support rgba are more common than those that support opacity, but in lower versions of ie rgba is not supported and opacity is supported

8. The attribute value and function of display

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-JAbGv3HB-1686967105037) (C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\ 1683804216661.png)]

9. What is the difference between display block, inline and inline-block?

block: will occupy a single line, multiple elements will start a new line, you can set width, height, margin and padding attributes;

inline: The element will not occupy a single line, setting the width and height attributes is invalid. However, you can set the margin and padding properties in the horizontal direction, but you cannot set the padding and margin in the vertical direction;

inline-block: Set the object as an inline object, but the content of the object is rendered as a block object, and the subsequent inline objects will be arranged in the same line.

10. What is the difference between display:none and visibility:hidden?

display:none hides the corresponding element, no space is allocated to it in the document layout, and the elements on each side of it will be closed, as if it never existed.
visibility:hidden hides the corresponding element, but retains the original space in the document layout.

11. The value of position, relative and absolute are relative to whom are they positioned?

Relative: relative positioning, relative to its own position in the normal document flow.
absolute: Generate absolute positioning, relative to the parent element whose positioning is not static at the nearest level. Finally found body
fixed: (old version of IE does not support) to generate absolute positioning, relative to the browser window or frame for positioning.
static: The default value, no positioning, the element appears in the normal document flow.
sticky: Generate sticky positioned elements, the position of the container is calculated according to the normal document flow.

12. What are the methods of hiding elements?

display: none: The rendering tree will not contain the dye object, so the element will not occupy a position in the page, nor will it respond to the bound listener event.

visibility: hidden: The element still occupies space in the page, but will not respond to the bound listener event

opacity: 0: Set the transparency of the element to 0 to hide the element. The element still occupies space in the page and can respond to the listening events bound to the element

position: absolute: Hide elements by removing them from the viewable area using absolute positioning

z-index: Negative value: to make other elements cover the element to hide it

transform: scale(0,0): scale the element to 0 to hide the element.

13. What is the difference between transition and animation?

  1. The triggering methods are different: transitionthe animation effect is triggered by the change of the CSS property value, while the animationanimation sequence needs to be specified by setting keyframes (keyframes).
  2. The control methods are different: transitionyou can only control the transition animation between the start and end states, but animationyou can specify multiple keyframes to control each stage of the element animation, including the start, middle and end moments of the animation, the transition state and duration, etc.
  3. The resource consumption is different: relatively speaking, animationthe browser consumes more resources, because it needs to calculate the animation effect between multiple key frames, and transitiononly needs to perform simple calculations between two states.
  4. Different compatibility: transitionRelatively speaking, it is more compatible with different browsers, but animationmay not work properly on some old browsers.

14. What is the difference between pseudo-elements and pseudo-classes?

Pseudo-elements: are objects created outside the document tree. For example, documentation cannot provide a mechanism for accessing the first word or line of an element's content. Pseudo-elements also provide some content distribution styles that do not exist in the source document, such as :before and :after can access the generated content. The content of a pseudo-element is actually the same as that of a normal DOM element, but it is only an element-based abstraction and does not exist in the document, so it is called a pseudo-element.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-mND9y0Cq-1686967105038) (C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\ 1683805298891.png)]

Pseudo-classes: are based on the characteristics of elements rather than their id, class, attributes or content. Generally speaking, the characteristics of an element cannot be inferred from the DOM tree, and it is dynamic. When the user interacts with the DOM, the element can gain or lose a pseudo-class. (The one exception here is that :first-child and :lang can be inferred from the DOM tree.)

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-0PrLEaC2-1686967105039) (C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\ 1683805345353.png)]

similarities and differences

same:

  • Neither pseudo-classes nor pseudo-elements appear in source files nor in the document tree. That is to say, pseudo-classes and pseudo-elements cannot be seen in the html source file.

difference:

  • Pseudo-classes are actually different states based on ordinary DOM elements, which are a certain feature of DOM elements. Pseudo-elements can create abstract objects that do not exist in the DOM tree, and these abstract objects are accessible.

15. Understanding of requestAnimationframe

HTML5 provides an API dedicated to requesting animation

grammar:

  • window.requestAnimationFrame(callback); Among them, callback is the function called to update the animation frame before the next redraw (that is, the callback function mentioned above). The callback function will be passed the DOMHighResTimeStamp parameter, which indicates the moment when requestAnimationFrame() starts to execute the callback function. This method is a macro task, so it will be executed after the micro task is executed.

Cancel animation:

  • Use cancelAnimationFrame() to cancel the execution of the animation. This method receives a parameter – the id returned by requestAnimationFrame by default. You only need to pass in this id to cancel the animation.

Advantage:

  • CPU energy saving
  • function throttling
  • Reduce DOM manipulation

16. What is the reason for the invisible blank space between li and li? How to solve it?

The browser will color the blank characters (spaces, newlines, tabs, etc.) between inline elements into a space. For aesthetics, usually a

  • put on one line, this results in
  • A newline character is generated after a newline, which becomes a space and occupies the width of one character.
  • solve:

    • for
    • Set float: left. Insufficient: Some containers cannot be set to float, such as the focus map for left and right switching.
    • will all
    • written on the same line. Insufficient: The code is not beautiful.
    • Set the character size inside to 0 directly, that is, font-size:0. insufficient:
      • The other character sizes in are also set to 0, and other character sizes need to be re-set, and there will still be blank spaces in the Safari browser.
    • eliminate
      • The character spacing letter-spacing:-8px, insufficient: This also sets the
      • The character space within the , so you need to put the
      • The character spacing within is set to the default letter-spacing:normal.

17. New features of CSS3

  • Add various css selectors (:not(.input): all nodes whose class is not 'input'): attribute selector, pseudo-class selector, pseudo-element selector, basic selector
  • Three Border Properties
    • border-radius: create a rounded border
    • border-shadow: add a shadow to the element
    • border-image: use an image to draw the border
  • background
    • background-clip: determine the background drawing area
    • background-origin: The setting starts from the upper left corner of the border-box, padding-box, and content-box
    • background-size: Adjust the size of the background image
    • background-break: The element can be broken into several independent boxes
  • letter
    • word-wrap: normal|break-word use the browser's default line break|allow line breaks within words
    • text-overflow: Set or retrieve how the current line exceeds the border of the specified container to display, the property consists of two values
      • clip: trim text
      • ellipsis: Show ellipsis to represent trimmed text
    • text-shadow: A shadow can be applied to the text. Ability to specify horizontal shadow, vertical shadow, blur distance, and shadow color
    • text-decoration: CSS3 began to support deeper rendering of text, and there are three specific attributes that can be provided
      • text-fill-color: Set the fill color inside the text
      • text-stroke-color: set the text boundary fill color
      • text-stroke-width: set the text border width
  • Color (new color representation rgba and hsla)
    • rgba is divided into two parts, rgb is the color value, a is transparency
    • hsla is divided into four parts, h is hue, s is saturation, l is lightness, a is transparency
  • transition transition, transform conversion, animation animation
  • flex elastic layout, Grid grid layout
  • media query

18. Create a picture format (brief description), the difference?

  • BMP: It is a bitmap that is lossless and supports both indexed and direct colors
  • GIF: is a lossless, indexed-color bitmap. Encode with LZW compression algorithm
  • JPEG: is a lossy bitmap in direct color. The advantage of JPEG pictures is that they use direct color, which benefits from richer colors
  • PNG-8: is a lossless bitmap using indexed colors.
  • PNG-24: is a lossless bitmap using direct color.
  • SVG: is a lossless vector graphics. SVG is a vector diagram meaning that the SVG picture consists of lines and curves and the means to draw them
  • WebP: It is a new image format developed by Google. WebP is a bitmap that supports both lossy and lossless compression and uses direct color.

19. Draw a straight line at 0.5px?

The test is the transform of css3

height: 1px;
transform: scale(0.5);

20. What are the meanings and usages of calc, support, and media?

  • @support is mainly used to detect whether the browser supports a certain attribute of CSS. In fact, it is a conditional judgment. If it supports a certain attribute, you can write a set of styles. If it does not support a certain attribute, you can also provide another set of styles. as a substitute.
  • The calc() function is used to dynamically calculate the length value. The calc() function supports "+", "-", "*", "/" operations;
  • @media query, you can define different styles for different media types.

21. What is the difference between px and em, rem?

px: absolute length unit, pixel px is relative to the screen resolution of the display
em: relative length unit, relative to the font-size of the text in the current object, the value of em is not fixed, and em will inherit the value of the parent element font-size (the reference is the font-size of the parent element)
rem: relative to the font-size of the html root element

22. What do 1rem, 1em, 1vh, 1px, vmin, and vmax represent?

  • rem
    rem is all lengths relative to the root element element. The usual practice is to set a font size for html elements, and then the length unit of other elements is rem.
  • The em of the font size of the em
    sub-element is relative to the font size of the parent element.
    The width/height/padding/margin of the element is relative to the font-size of the element if em is used
  • The full names of vw/vh
    are Viewport Width and Viewport Height. The width and height of the window are equivalent to 1% of the screen width and height. However, the % unit is more appropriate when dealing with width, and the vh unit is better when dealing with height.
  • px
    px pixel (Pixel). Relative length unit. Pixel px is relative to the screen resolution of the monitor.
    The resolution of a general computer is {1920 1024} and other different resolutions
    1920
    1024. The former has a screen width of 1920 pixels in total, while the latter has a height of 1024 pixels.
  • vmin/vmax: Take the minimum value of the height and width of the window as the reference/take the maximum value of the height and width of the window as the reference.
    • If the window height is 1080 and width is 1920 then. 1vmin=1080px/100=10.8px 1vmax=1920px/100=19.2px.

23. CSS draw a triangle?

This is a simple css test. While using the component library, don’t forget the native css

.a {
    width: 0;
    height: 0;
    border-width: 100px;
    border-style: solid;
    border-color: transparent #0099CC transparent transparent;
    transform: rotate(90deg); /*顺时针旋转90°*/
}
<div class="a"></div>

24. Elements are centered horizontally and vertically

  • Use positioning +margin:auto
  • Use positioning + margin: negative value
  • Use positioning + transform
  • table layout
  • flex layout
  • grid layout

25. Principles of Responsive Layout

  1. What is Responsive: A web page design layout, the design and development of the page should respond and adjust accordingly according to user behavior and device environment (system platform, screen size, screen orientation, etc.)
  2. Basic principle: Detect different device screen sizes through media queries for processing. In order to handle mobile terminals, there must be a meta declaration viewport in the head of the page.
  3. Method to realize
    • media query
    • percentage layout
    • vw/vh
    • rem

26. CSS positioning method?

static: The element box is generated normally. Block-level elements generate a rectangular box as part of the document flow, while inline elements create one or more line boxes to place within their parent element.

relative: The element box is offset by a certain distance. The element retains its unpositioned shape, and the space it originally occupied is preserved.

absolute: The element box is completely removed from the document flow and positioned relative to its containing block. The containing block may be another element in the document or the initial containing block. The space the element previously occupied in the normal document flow is closed as if the element did not exist. The element is positioned to generate a block-level box, regardless of the type of box it originally generated in normal flow.

fixed: The element box behaves like setting position to absolute, but its containing block is the viewport itself.

27. What is css sprite (Sprite image, sprite image) and what are its advantages and disadvantages?

CSSSprites (sprite images) include all the images involved in a page into a large image, and then use the combination of CSS background-image, background-repeat, and background-position attributes for background positioning.

advantage:

  • Reduce HTTP requests and greatly improve page loading speed
  • Increase the repetition of image information, increase the compression ratio, and reduce the image size
  • It is easy to change the style, you only need to modify the color or style on one or several pictures

shortcoming:

  • Picture merging trouble
  • troublesome maintenance

28.设备像素、css像素、设备独立像素、dpr、ppi 之间的区别?

设备像素:又称为物理像素, 指设备能控制显示的最小物理单位,不一定是一个小正方形区块,也没有标准的宽高,只是用于显示丰富色彩的一个“点”而已

css像素: 适用于web编程,在 CSS 中以 px 为后缀,是一个长度单位 。css中长度分为两类:绝对单位和相对单位,px属于相对单位

设备独立像素: 与设备无关的逻辑像素,代表可以通过程序控制使用的虚拟像素,是一个总体概念 。我们常说的分辨率,不严谨来讲是指的设备独立像素。在javascript中我们可以通过 window.screen.width/ window.screen.height 来查看

dpr:设备像素比, 代表设备独立像素到设备像素的转换关系

ppi:像素密度, 表示每英寸所包含的像素点数目

29.margin 和 padding 的使用场景

需要在border外侧添加空白,且空白处不需要背景 (色)时,使用 margin;

需要在border内测添加空白,且空白处需要背景(色) 时,使用 padding。

30.对line-height的理解,赋值方式

概念:

  • line-height 属性设置行间的距离(行高),说的直白一点,就是设置两段段文本之间的距离如果我们把一段文本的line-height设置为父容器的高度就可以实现文本垂直居中了。

原理:

  • 我们可以理解为将div分为三份,分别为上边距,内容,下边距。举例:div高度100px,字体为16px,那么上下边距计算为(100px-16px)/2

赋值方式:

  • 带单位:px 是固定值,而 em 会参考父元素 font-size 值计算自身的行高
  • 纯数字:会把比例传递给后代。例如,父级行高为 1.5,子元素字体为 18px,则子元素行高为 1.5 * 18 = 27px
  • 百分比:将计算后的值传递给后代

31.谈谈你对BFC的理解?触发条件?应用场景?

Concept: BFC is the block-level formatting context, which is a rendering area in the page and has its own set of rendering rules. The purpose of BFC is to form a space that is completely independent from the outside world.让内部的子元素不会影响到外部的元素

Triggering conditions:

  • The root element, the HTML element
  • Floating element: float value is left, right
  • The overflow value is not visible, it is auto, scroll, hidden
  • display的值为inline-block、inltable-cell、table-caption、table、inline-table、flex、inline-flex、grid、inline-grid
  • The value of position is absolute or fixed

Application scenario:

  • Prevent overlapping margins
  • clear internal float
  • Adaptive multi-column layout

32. How to implement two-column layout, adaptive on the right side? Adaptive in the middle of the three-column layout?

两栏布局

  • Use float to float the left column on the left, and use margin-left on the right to expand the width of the left column. Add BFC to the parent element and enable it with overflow: hidden.
  • flex layout

三栏布局

  • The principle of the following three methods is the same as the first method of the two-column layout
    • Use float on both sides and margin in the middle
    • Use absolute on both sides and margin in the middle
    • Use float and negative margin on both sides
  • flex layout
  • display: table implementation
    • Set display: table as a table, and set table-layout: fixed` to indicate that the column width is determined by itself, rather than automatically calculated.
    • The left, middle and right of the inner layer are set as table cells by display: table-cell.
    • Set a fixed width on the left and right, and set width in the middle: 100% to fill the remaining width
  • grid grid layout

33. Talk about flexbox (elastic box layout model), and applicable scenarios?

Understanding: flex layout means "elastic layout", which can realize various page layouts in a simple, complete and responsive manner. By default, there are two axes in the container, the main axis and the cross axis, which are in a 90-degree relationship. Items are arranged along the main axis by default, and flex-directionthe direction of the main axis is determined by

Attributes:

  • flex-direction determines the direction of the main axis
  • flex-wrap determines whether the items in the container can wrap
    • wrap, wrap
  • alignment of justify-content items on the main axis
    • flex-start (default): left-aligned
    • flex-end: right alignment
    • center: centered
    • space-between: both ends are aligned, and the intervals between items are equal
    • space-around: two items are equally spaced on both sides
  • align-items How items are aligned on the cross axis
    • flex-start: The starting point of the cross axis is aligned
    • flex-end: Align the end of the cross axis
    • center: Align the midpoint of the cross axis 垂直居中
    • baseline: the baseline alignment of the first line of text in the item
    • stretch (default): If the item does not have a height set or is set to auto, it will take up the height of the entire container
  • align-content

34. Introduce the grid grid layout

Understanding: GridLayout is a grid layout, which is a two-dimensional layout method. It is a framework layout structure formed by two sets of grid lines that intersect vertically and horizontally, and can handle rows and columns at the same time.

Container properties:

  • display: grid The container is a block-level element/inline-grid The container is an inline element
  • grid-template-columns attribute, grid-template-rows attribute:
    • Set the column width and row height by several rows and columns. If the width and height are repeated, repeat(3,200px) can be used to represent 3 rows and columns, 200px width and height
  • grid-row-gap property, grid-column-gap property, grid-gap property
    • Set the spacing between rows and columns, grid-gap is shorthand for both
  • grid-template-areas attribute: used to define the area
  • grid-auto-flow attribute: After dividing the grid, the child elements of the container will be in order, and the order is determined by grid-auto-flow

Project properties:

  • grid-column-start attribute, grid-column-end attribute, grid-row-start attribute, and grid-row-end attribute: specify the four borders where the grid item is located, and which grid line is located respectively, so as to specify the item s position
  • grid-area attribute: The attribute specifies in which area the item is placed. Areas are divided by the grid-template-areas property
  • justify-self attribute, align-self attribute, and place-self attribute

35. What are the CSS3 animations?

  • transition implements gradient animation

  • transform transform animation

  • animation implements custom animation

36. How to understand reflow and redraw? Under what circumstances will it be triggered?

  • Reflow: The layout engine calculates the size and position of each box on the page based on various styles
  • Redrawing: After calculating the position, size and other attributes of the box model, the browser draws according to the characteristics of each box

Triggering conditions:

  • Reflow:
    • Add or remove visible DOM elements
    • The position of the element changes
    • The size of the element changes (including margins, inner borders, border size, height and width, etc.)
    • Content changes, such as text changes or an image is replaced by another image of a different size
    • When the page starts to render (this cannot be avoided)
    • The browser's window size changes (because reflow calculates the position and size of elements based on the size of the viewport)
  • Redraw ------触发回流一定会触发重绘
    • color modification
    • Text Orientation Modification
    • shadow modification

37. If optimization is to be done, what are the methods of CSS to improve performance?

  • Inline above the fold critical CSS
  • avoid css expressions
  • Load CSS asynchronously
  • resource compression
  • Use selectors wisely
  • Reduced use of expensive properties like box-shadow/// transparency/ etcborder-radiusfilter:nth-child
  • Do not use @import

38. How to realize the ellipsis style of single-line/multi-line text overflow?

single line text overflow

  • white-space: Set the text to be displayed on one line, and cannot wrap
  • overflow: If the length of the text exceeds the limited width, the excess content will be hidden
  • text-overflow: specifies that when the text overflows, an ellipsis is displayed to represent the trimmed text
    • clip: when the overflow part of the text in the object is cut off
    • ellipsis: Show ellipsis markers (…) when text inside an object overflows
    • text-overflowIt will only take effect when the overflow:hiddenandwhite-space:nowrap

Multiline text overflow omitted

  • Truncation based on height – pseudo element + positioning
    • position: relative: Absolute positioning for pseudo-elements
    • overflow: hidden:文本溢出限定的宽度就隐藏内容)
    • line-height: 20px:结合元素高度,高度固定的情况下,设定行高, 控制显示行数
    • height: 40px:设定当前元素高度
    • ::after {} :设置省略号样式 – 设置伪元素
    • position: absolute:给省略号绝对定位
    • content:“…”
  • 基于行数截断 – 纯css
    • -webkit-line-clamp: 2:用来限制在一个块元素显示的文本的行数,为了实现该效果,它需要组合其他的WebKit属性)
    • display: -webkit-box:和-webkit-line-clamp结合使用,将对象作为弹性伸缩盒子模型显示
    • -webkit-box-orient: vertical:和-webkit-line-clamp结合使用 ,设置或检索伸缩盒对象的子元素的排列方式
    • overflow: hidden:文本溢出限定的宽度就隐藏内容
    • text-overflow: ellipsis:多行文本的情况下,用省略号“…”隐藏溢出范围的文本

39.让Chrome支持小于12px 的文字方式有哪些?区别?

Chrome 中文版浏览器会默认设定页面的最小字号是12px,英文版没有限制 。

解决方案:

  • zoom : “变焦”,可以改变页面上元素的尺寸,属于真实尺寸
  • -webkit-transform:scale(): 针对chrome浏览器,加webkit前缀,用transform:scale()这个属性进行放缩
  • -webkit-text-size-adjust:none: 该属性用来设定文字大小是否根据设备(浏览器)来自动调整显示大小

区别:

  • Zoom 非标属性,有兼容问题,缩放会改变了元素占据的空间大小,触发重排
  • -webkit-transform:scale() 大部分现代浏览器支持,并且对英文、数字、中文也能够生效,缩放不会改变了元素占据的空间大小,页面布局不会发生变化
  • -webkit-text-size-adjust对谷歌浏览器有版本要求,在27之后,就取消了该属性的支持,并且只对英文、数字生效

40. Tell me about your understanding of Css preprogrammed languages ​​(sass, less)? What are the differences?

Understanding: The language has been expanded Css, and functions such as variables, mixins, and functions have been added to make it Csseasier to maintain and facilitate. Essentially, preprocessing is Cssa superset of . Contains a set of custom grammars and a parser. According to these grammars, you can define your own style rules. These rules will eventually compile and generate corresponding Cssfiles through the parser.

Which are: sass, less,stylus

Compare less and sass:

  • Same point:
    • First of all, both sass and less are css precompiled processing languages. They introduce mixins, parameters, nesting rules, operations, colors, namespaces, scopes, JavaScript assignments, etc. to speed up css development efficiency. Of course, both of them can be used together. Front-end build tools such as gulp and grunt use
  • the difference:
    • Less is based on JavaScript and is processed on the client side, so use npm when installing
    • Sass is based on ruby ​​so it is processed on the server
  • Advantages and disadvantages of less
    • Advantages: less is simple and easy to use; it belongs to the basic expansion of css; less is more suitable for writing styles on static interfaces
    • Disadvantage: The JavaScript engine needs extra time to process the code and then output the modified CSS to the browser
  • Advantages and disadvantages of sass
    • Advantages: Powerful, richer expansion Sass is suitable for games or other effects that require logic to replace different styles
    • Disadvantages: complex and unfriendly for novices

41. What is FOUC? How to avoid it?

FOUC: Flickering of unstyled content can also be called short-term failure of document style, which mainly refers to the flickering phenomenon caused by the HTML has been loaded but the style sheet is not loaded, and then the style sheet is loaded again.

How to avoid:

  • Style sheet front : according to the order of browser rendering, CSS is introduced or embedded in
  • Try to use link to avoid using @import ,

42. What are the advantages and disadvantages of clearing floating methods?

  • Extra label method: For whom to clear the float, add an additional blank label after it

    • Advantages: Easy to understand and easy to write. (not recommended)
    • Disadvantages: Many meaningless tags are added, and the structure is relatively poor.
  • The overflow method added by the parent: The clear floating effect can be achieved by triggering the BFC.

    • Advantages: Simple, less code, good browser support
  • Disadvantages: When the content increases, it is easy to cause the content to be hidden without automatic line wrapping, and the elements that need to overflow cannot be displayed. Cannot be used in conjunction with position, because the excess size will be hidden.

  • Use the after pseudo-element to clear the float: The :after method is an upgraded version of the empty element, and the advantage is that it does not need to be tagged separately.

    • Advantages: In line with the idea of ​​closed floating, the structure is semantically correct, and it is not easy to have strange problems (currently: large websites are used, such as: Tencent, Netease, Sina, etc.)
    • Disadvantages: Since IE6-7 does not support

43. Should odd or even fonts be used in web pages? why?

  • Even numbers are relatively easier to form a proportional relationship with the rest of the web design

44. If you need to write animation manually, how long do you think the minimum time interval is, and why? (Ali)

  • The default frequency of most displays is 60Hz, that is, 1refresh 60times per second, so the theoretical minimum interval is1/60*1000ms = 16.7ms

45. The principle and advantages and disadvantages of base64?

  • Advantages can be encrypted, reducing HTTTPrequests
  • The disadvantage is that it needs to consume CPUcodec

46. ​​Fluid layout, holy grail layout, double flying wing layout?

The difference between the Holy Grail layout and the double-flying wing layout:

  • Same point
    • The functions of the two are the same, both are to achieve a three-column layout with fixed width on both sides and adaptive width in the middle , and the middle part should be written in front of the HTML code, so that it will be loaded and rendered first.
  • difference
    • The main difference is that when solving the problem that the middle part is blocked, the solutions adopted are different. The holy grail layout is to set padding-left and padding-right on the parent element, set the position to relative for the content on the left and right sides, and move the content on the left and right to make the content on the left and right sides well displayed, while the double-flying wing layout In the outer layer of the div in the middle, another div is set to place the content, and margin-left and margin-right are set for the middle div.

47. The role of postcss

PostCSS is a tool for transforming CSS using JS plugins. These plugins can support variables and mixins, transpile future CSS syntax, inline images, and more.

effect:

  • Support future css: use cssnext to write future css (postcss-cssnext plugin)
  • The compilation speed is greatly improved. PostCSS claims to be 3-30 times faster than preprocessors.
  • Rich plug-in system, free your hands.
  • Modularization of css, which limits the scope to components, avoids the problem of global scope, and no longer has to worry about duplication of style names

Postcss is a css post-processor that dynamically compiles css, that is, compiles at runtime.

48. Does css have a content attribute? what's the effect? What is the application?

The properties of css contentare specifically applied to before/afterpseudo-elements, which are used to insert generated content. The most common application is to use pseudo-classes to clear floats.

49. Horizontal centering method

  • The element is an inline element, set the parent elementtext-align:center
  • If the element width is fixed, you can set left and right marginto auto;
  • Absolute positioning and movement:absolute + transform
  • Use flex-boxthe layout, specify justify-contentthe attribute as center
  • displaySet astabel-ceil

50. Talk about the animation and transition of CSS3 in detail

  • animation
    • css3 animationis a new animation attribute of css3. Each frame of this css3 animation is @keyframesdeclared by passing, keyframesdeclaring the name of the animation, and defining the animation process by from, or percentageto
    • The state of each frame of animation elements is used to animation-namerefer to this animation. At the same time, css3 animation can also define the duration of the animation, the start time of the animation, the direction of the animation, the number of animation loops, and the way the animation is played.
    • These related animation sub-properties are:
      • animation-nameDefine animation name
      • animation-durationDefines the duration of the animation to play
      • animation-delayDefines how long the animation delays to play
      • animation-directionDefines the playback direction of the animation
      • animation-iteration-countDefine play count
      • animation-fill-modeDefine the state after the animation is played
      • animation-play-stateDefine the playback state, such as pausing, running, etc.
      • animation-timing-functionDefine the playback mode, such as constant speed playback, deceleration playback, etc.
  • transition
    • transition-property: specifies the css property name for setting the transition effect
    • transition-duration : specifies how many seconds or milliseconds it takes to complete the transition effect
    • transition-timing-function : Specifies the transition function, specifying the speed curve of the speed effect
    • transition-delay : Specifies the delay time to start appearing

51. What is CSS Hack? Common Hacks

Description: By adding some special symbols in the CSS style, different browsers can recognize different symbols (there is a standard for what kind of symbols are recognized by browsers, CSS hack is to let you remember this standard), In order to achieve the purpose of applying different CSS styles.

Common hacks:

  • Attribute-level Hack: For example, IE6 can recognize the underscore " " and the asterisk "*", IE7 can recognize the asterisk "*", but not the underscore " " , and firefox can't recognize both.
  • Selector-level Hack: For example, IE6 can recognize html .class{}, and IE7 can recognize +html .class{} or *:first-child+html .class{}.
  • IE conditional comment Hack: IE conditional comment is a non-standard logical statement provided by Microsoft IE5.

52. How do browsers parse CSS selectors?

  • The way browsers parse CSS selectors is from right to left

53. How to write the detached style module, and express ideas

  • CSS can be split into two parts: public CSS and business CSS:
    • The color scheme, font, and interaction of the website are extracted as public CSS. This part of CSS naming should not involve specific business
    • For business CSS, it is necessary to have a unified naming and use a common prefix. You can refer to Object-Oriented CSS

54. Is the vertical percentage setting of the element relative to the height of the container?

不是

Both vertical and horizontal percentage settings are relative to the container 宽度. We can verify by margin and padding

55. What is the principle of full screen scrolling? Which properties of CSS are used?

  • The principle is similar to the principle of picture carousel, beyond the hidden part, it will be displayed when scrolling
  • Possible CSS properties:overflow:hidden; transform:translate(100%, 100%); display:none;

56. After setting the element to float, how will the display value of the element change

After the element is set to float, displaythe value of the element will automatically becomeblock

57. When will display:inline-block display gaps?

  • inline-blockSpacing occurs when adjacent elements are separated by newlines or spaces
  • Non- inline-blockhorizontal elements set to inline-blockalso have horizontal spacing
  • vertical-align:top;Vertical gaps can be eliminated with the help of
  • You can font-size:0;add the required font size in the child element at the parent level to eliminate the vertical gap
  • Putting lithe tags on the same line can eliminate the vertical gap, but the code is less readable

58. What is the difference between pageX, clientX, screenX, and offsetX?

pageX/Y: For the entire page, including the length of the body part that is rolled away

clientX/Y: The x, y coordinates of the click position from the current body visible area

screenX/Y: The x, y coordinates of the click position from the current computer screen

offsetX/Y: Relative to the x, y coordinates of the parent box with positioning

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rXHtNM4t-1686967105041)(C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\1683882788135.png)]

59.如何对不同IE版本浏览器做兼容测试?

使用工具切换IE版本,然后在IE浏览器运行测试

60.border- radius详解

在开发中我们经常通过正方形设置border- radius:50%来实现圆

border-radius参数选择:

  • border-radius:10px;将创建四个大小一样的圆角
  • border-radius:10px 15px 10px 15px; 四个值分别表示左上角、右上角、右下角、左下角
  • border-radius:10px 15px; 第一个值表示左上角、右下角;第二个值表示右上角、左下角
  • border-radius:10px 15px 5px; 第一个值表示左上角;第二个值表示右上角、左下角;第三个值表示右下角。

61.让页面里的字体变清晰,变细用CSS怎么做?

-webkit-font-smoothing: antialiased;

63.CSS3渐变?

CSS3 定义了两种类型的渐变(gradients):

  • 线性渐变 - 向下/向上/向左/向右/对角方向
  • 径向渐变 -(Radial Gradients)- 由它们的中心定义

线性渐变:

  • 语法:background-image:linear-gradientdirection,color-stop1,color-stop2,……);
    • direction:渐变方向/角度,可选(45deg,to bottom,to top,to right,to left,to left top…)
    • color-stop:选择颜色rgba可以设置透明度,也可以设置色标点区域 例:rgba(255,255,255,0.3) 20%

Radial Gradient:

  • 语法:background-image: radial-gradient(shape size at position, start-color, …, last-color);
    • The shape parameter defines the shape. It can be the value circle or ellipse. Among them, circle represents a circle, and ellipse represents an ellipse. The default value is ellipse.
    • size: Mainly used to determine the end shape size of the radial gradient. If omitted, its default value is "farthest-corner"
    • at position start point: the position of the center point, which can be a keyword (horizontal direction – left, center, right, vertical direction – top, center, bottom), specific value or percentage.

64. What is the difference between responsive layout and adaptive layout?

  • Responsive layout refers to using CSS media queries to set different styles according to different devices or viewport widths to adapt to different screen sizes, so as to realize automatic adjustment and optimization of the page. Responsive layout can make the website display optimally on multiple devices such as desktop, tablet and mobile phone.
  • Adaptive layout refers to selecting an appropriate layout method according to the screen size to make the page look more beautiful and readable on different devices. Adaptive layout is relatively more fixed. Its page layout is usually composed of several fixed layouts. Different layout combinations are selected for display under different screen sizes, instead of directly changing the style like responsive layout.

65. Several situations where z-index fails

  • The position attribute is not set or the value is static: If you want to use the z-index attribute, you need to first set the element's position attribute to relative, absolute or fixed. Otherwise, even if z-index is set, it won't make it work.
  • The z-index value of the parent element is higher than that of the child element: When a parent element and its child elements have z-index set, the z-index of the child element may be invalid.
  • Invalid z-index of floated elements: When using floated elements, the z-index property may not work. This is because floating itself has a certain cascading nature, and the stacking order of floating elements is determined by their sequence in the document flow.

66. Change the display value after float?

block

67. Anchors in css

<a name="go">来我这里</a>
......
<a href="#go">我来了</a>

You can use the id attribute to replace the name attribute, use the id to define the anchor point, and locate any label. The name attribute can only be located for the a tag.

68. Solution to 1px problem on mobile

  • Scaling with css pseudo-elements::after + transfrom
    • Advantages: All models are compatible, real 1px is realized, and the corners can be rounded. Good for old projects.
    • Disadvantage: The after pseudo-element is temporarily used, which may affect the clearing of floating.
  • Set the scale value of viewport
    • Advantages: Compatible with all models, directly writing 1px cannot be more convenient.
    • Disadvantages: Applicable to new projects, old projects may be changed a lot.
  • Use the component library vant/ant-design-mobile

69. Prevent the default left and right sliding behavior of mobile H5 development browsers

html{
    
    
    touch-action:none;
}
//此时上下左右都不可滑动
--------改动
html{
    
    
touch-action:none;
touch-action:pan-y;
}

70. Comparison of positioning position and transform moving elements in CSS

  • In terms of performance: transform performance is much higher than position
  • Moved by translate, the element will still occupy its original space. If you move by position, the position will be changed to trigger redrawing

71.margin-left:auto,margin-right:auto,margin:auto区别

margin-left:auto 右对齐

margin-right:auto 左对齐

margin: auto居中

72.css full screen scrolling

overflow-y;overflow-x;scroll-snap-type;scroll-snap-align;required attribute

<style>
        html,
        body {
     
     
            height: 100%;
            margin: 0;
        }

        ul {
     
     
            margin: 0;
            /* scroll-behavior: smooth 让页面在滚动时拥有平滑的过渡效果,而不是瞬间跳转 */
            scroll-behavior: smooth;
            font-size: 40px;
            width: 100%;
            height: 100%;
            /* 
            overflow-y: auto 表示当内容超出元素的高度时,元素会显示垂直方向的滚动条以便用户浏览。如果内容不超出元素的高度,则不会显示滚动条。
            overflow-x: hidden 则表示当内容超出元素的宽度时,元素不会显示水平方向的滚动条,同时超出部分的内容也将被隐藏。
            */
            overflow-y: auto;
            overflow-x: hidden;
            border: 1px solid #000;
            /* 
            scroll-snap-type: y mandatory; 表示在垂直方向上开启滚动对齐功能,并强制要求元素对齐到滚动容器的边缘。这样可以确保每个子元素都在独立的、整数倍的位置停留,从而实现更加规整的页面布局。
            */
            scroll-snap-type: y mandatory;
            /*设置父级*/
            padding: 0;
        }

        li {
     
     
            height: 100%;
            width: 100%;
            flex-shrink: 0;
            /* 
            scroll-snap-align: center; 则表示对齐方式为中心对齐,当子元素的中心点(水平轴和垂直轴的中心点)与滚动容器的中心点重合时,就会触发对齐效果。
            */
            scroll-snap-align: center;
            /*子级设置*/
            text-align: center;
        }

        li:nth-child(1) {
     
     
            background-color: teal;
        }

        li:nth-child(2) {
     
     
            background-color: gold;
        }

        li:nth-child(3) {
     
     
            background-color: green;
        }
    </style>
	<ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
    </ul>

73. Disadvantages of table layout

  • The HTML structure is not semantic: using table layout requires the use of a large number of table, row and cell elements, which will cause the HTML structure to be non-semantic. When using the table layout, the meaning of the HTML structure is obscured, which will cause certain difficulties for people who read and understand the HTML code.
  • Code redundancy: In order to achieve complex layout effects, it is often necessary to use a large number of rowspan and colspan attributes, which will make the HTML code lengthy and difficult to maintain.
  • Difficult to adapt to mobile devices: The implementation of table layout usually requires specifying the width and height of the table, so it does not perform well on mobile devices, resulting in truncated or reduced page content.
  • Low rendering performance: Since browsers need to parse a large number of table elements, using table layout will affect the performance of page rendering.
  • 不利于 SEO:由于 table 布局不具备语义化,这会导致搜索引擎难以理解页面的结构和内容,降低网站的 SEO(搜索引擎优化)效果。
  • 不利于响应式布局:由于 table 布局需要指定表格的宽度和高度,因此难以适应不同尺寸的屏幕。对于实现响应式布局,table 布局效果并不是很理想。

三、HTML / CSS 混合篇

1. HTML5、CSS3 里面都新增了那些新特性?

HTML5

  • 新的语义标签
    • article 独立的内容。
    • aside 侧边栏。
    • header 头部。
    • nav 导航。
    • section 文档中的节。
    • footer 页脚。
  • 画布(Canvas) API
  • 地理(Geolocation) API
  • 本地离线存储 localStorage 长期存储数据,浏览器关闭后数据不丢失;
    sessionStorage 的数据在浏览器关闭后自动删除
  • 新的技术webworker, websocket, Geolocation
  • 拖拽释放(Drag and drop) API
  • 音频、视频API(audio,video)
  • 表单控件,calendar、date、time、email、url、searc

CSS3

  • 2d,3d变换
  • Transition, animation
  • 媒体查询
  • 新的单位(rem, vw,vh 等)
  • 圆角(border-radius),阴影(box-shadow),对文字加特效(text-shadow),线性渐变(gradient),旋转(transform)transform:rotate(9deg) scale(0.85,0.90) translate(0px,-30px) skew(-9deg,0deg);//旋转,缩放,定位,倾斜
  • rgba

四、JS 篇

1. JS 数据类型 ?存储上的差别?

数据类型主要包括两部分:

  • 基本数据+类型: Undefined、Null、Boolean、Number 和 String,Symbol(创建后独一无二且不可变的数据类型 )
  • 引用数据类型: Object (包括 Object 、Array 、Function)

存储区别:

  • 基本数据类型存储在栈中
  • 引用类型的对象存储于堆中

2.数组常用方法?

增:

  • push() 向数组的末尾添加一个或更多元素,并返回新的长度
  • unshift() 在数组开头添加任意多个值,然后返回新的数组长度
  • splice() 传入三个参数,分别是开始位置、0(要删除的元素数量)、插入的元素,返回空数组
  • concat() 首先会创建一个当前数组的副本,然后再把它的参数添加到副本末尾,最后返回这个新构建的数组,不会影响原始数组

删:

  • pop() 方法用于删除数组的最后一项,同时减少数组的length 值,返回被删除的项
  • shift() 方法用于删除数组的第一项,同时减少数组的length 值,返回被删除的项
  • splice() 传入两个参数,分别是开始位置,删除元素的数量,返回包含删除元素的数组
  • slice() 传入两个参数,分别是开始位置和结束位置,不包括结束值,返回一个新数组,不影响原数组

改:

  • splice() 传入三个参数,分别是开始位置,要删除元素的数量,要插入的任意多个元素,返回删除元素的数组,对原数组产生影响

查:

  • indexOf() 返回要查找的元素在数组中的位置,如果没找到则返回 -1
  • includes() 返回要查找的元素在数组中的位置,找到返回true,否则false

3.JavaScript字符串的常用操作方法有哪些?

增:

  • 字符串可以通过‘+’以及${}进行字符串拼接
  • concat 用于将一个或多个字符串拼接成一个新字符串

删:三个函数都接收一个或两个参数,跟数组中slice相似

  • slice()
  • substr() 接受两个参数:起始索引和要提取的字符数
  • substring() 接受两个参数:起始索引和结束索引 不包括结束位置的字符

改:

  • trim()、trimLeft()、trimRight() 删除前、后或前后所有空格符,再返回新的字符串
  • repeat() receives an integer parameter, indicating how many times to copy the string, and then returns the result after splicing all the copies
  • padStart(), padEnd() copy the string, receive two parameters, the first parameter is the length, the second parameter is the character to be filled, if it is less than the specified length, fill the character on the corresponding side (end/start) , until the length condition is satisfied
  • toLowerCase(), toUpperCase() case conversion

check:

  • chatAt() returns the character at the given index, specified by the integer parameter passed to the method
  • indexOf() searches the incoming string from the beginning of the string and 返回位置(returns -1 if not found)
  • startWith() searches the passed in string from the string, 判断开头字符串是否与期待值相同, and returns a boolean indicating whether it contains
  • includes() searches the passed in string from the string, 判断字符串是否包含期待值, and returns a boolean indicating whether it is included

4. Common conversion methods and template matching methods for JavaScript strings?

Conversion method:

  • split() splits the string into each item in the array according to the specified delimiter

Template matching method:

  • match() receives a parameter, which can be a regular expression string or an RegExpobject, and returns an array
  • search() receives a parameter, which can be a regular expression string or an RegExpobject, and returns the matching index if found, otherwise returns -1
  • replace() receives two parameters, the first parameter is the matching content, and the second parameter is the replaced element (function available)

5. Type conversion mechanism in JavaScript

Display conversion:

  • Number()
    • String: If it can be parsed as a numeric value, convert to the corresponding numeric value
    • String: If it cannot be parsed as a number, return NaN
    • Empty strings are converted to 0
    • Boolean value: true turns into 1, false turns into 0
    • undefined:转成 NaN
    • null:转成0
    • Objects: usually converted to NaN (except for arrays containing only a single value)
  • parseIntCompared with parseInt() Number, it is not so strict. parseIntThe function parses characters one by one, and stops when it encounters characters that cannot be converted.
  • String() can convert any type of value into a string
    • Special: Return if an object is accepted [object,object] If it is an array [1,2,3] return 1,2,3
  • Boolean() can convert any type of value into a Boolean value

Implicit conversion:

  • In +the operation, once there is a string, the string splicing operation will be performed
  • Except +for the possibility to convert the operator to a string, other operators will automatically convert the operator to a value. Commonly used is to convert a string to a numeric string -0 = numeric

6. What is the difference between null and undefined?

  • Null and undefined cannot be judged by ==.
  • undefined
    • This variable is fundamentally undefined
  • Hidden Null
  • null
    • The value is defined, but it does not point to any object in memory
  • declarative null

7. What is the difference between "===" and "=="?

==: Returns if the operands are equaltrue

  • Both are simple types, strings and Boolean values ​​will be converted to numeric values, and then compared
  • Simple types are compared with reference types, the object is converted to a value of its original type, and then compared
  • Both are reference types, compare whether they point to the same object
  • null and undefined are equal
  • Returns false if NaN exists

===: returns true only if the operands are equal without type conversion, need to check the data type

the difference:

  • The equality operator (==) will do it 类型转换, and then compare the values, and the equality operator will not do type conversion

8. "What does eval do?

Its function is to parse the corresponding string into JS code and run it;
you should avoid using eval, which is unsafe and very performance-consuming (2 times, once parsed into js statement and once executed).

9. What are the characteristics of arrow functions?

Do not need the function keyword to create a function
Omit the return keyword
Change this to point to

10. What is the difference between var, let, and const?

var variable hoisting exists.
let is only accessible at block-level scope.
const is used to define constants, which must be initialized and cannot be modified (objects are special)

11. What exactly does the new operator do?

1. Create an empty object, and the this variable refers to the object, and also inherits the prototype of the function.
2. Properties and methods are added to the object referenced by this.
3. The newly created object is referenced by this, and finally returns this implicitly.

12. What is the difference between deep copy and shallow copy? How to implement a deep copy?

Shallow copy: Refers to the creation of new data, which has an exact copy of the original data attribute value, and the two objects point to the same address

Deep copy: Deep copy opens up a new stack, the two objects are the same, but correspond to two different addresses, modify the properties of an object,不会改变另一个对象的属性

How to implement deep copy:

  • JSON.stringify()
  • handwritten loop recursion
  • _.cloneDeep()
  • MessageChannel added
  • jquery extend

13. Understanding of scope chain

  • The role of the scope chain is to ensure that the variables and functions that have the right to access in the execution environment are in order. The variables of the scope chain can only be accessed upwards, and the variables will be terminated when they access the object. The variables accessed downward by the scope chain will not be accessed window. Allowed
  • Simply put, 作用域就是变量与函数的可访问范围the scope controls the visibility and life cycle of variables and functions

14. JavaScript prototype, prototype chain? What are the characteristics?

  • prototype:
    • JavaScriptAll objects of , contain an [__proto__]internal property, which corresponds to the prototype of the object
    • The JavaScript function object, in addition to the prototype [__proto__], also presets prototypethe property
    • When a function object is used as a constructor to create an instance, the prototype attribute value will be used as the prototype of the instance object[__proto__]
  • Prototype chain:
    • When the attribute/method called by an object does not exist, it will go to its [__proto__]associated predecessor prototypeobject to find it
    • If not found, it will go to the predecessor associated with the prototypeprototype to find it. And so on until a property/method or is found. Thus forming the so-called "prototype chain"[__proto__]prototypeundefined
  • Prototype features:
    • JavaScriptObjects are passed by reference, and when a prototype is modified, related objects inherit the change

15. Please explain what is an event proxy

  • Event proxy ( Event Delegation), also known as event delegation. is JavaScripta common technique for binding events commonly used in . As the name implies, "event proxy" is to entrust the event that originally needs to be bound to the parent element, and let the parent element take on the role of event monitoring. The principle of event proxy is the event bubbling of DOM elements. The benefit of using an event proxy is that it can improve performance
  • It can save a lot of memory usage and reduce event registration. For example, it is great to proxy all events on tablethe Internet .tdclick
  • It can be realized that when a new sub-object is added, there is no need to bind it again

16. How does Javascript implement inheritance?

  • Constructor binding: Use the callor applymethod to bind the constructor of the parent object to the child object
  • Instance inheritance: point the prototype of the child object to an instance of the parent object Cat.prototype = new Animal();
  • Copy inheritance: If all the properties and methods of the parent object are copied into the child object
  • Prototype inheritance: point the child object prototypeto the parent object's prototypeF.prototype = Parent.prototype;
  • ES6syntactic sugarextends:class ColorPoint extends Point {}

17. Talk about the understanding of the This object

  • thisalways refer to the direct caller of the function (not the indirect caller)
  • 如果有new关键字,this指向new出来的那个对象
  • 在事件中,this指向触发这个事件的对象,特殊的是,IE中的attachEvent中的this总是指向全局对象Window

18.事件模型

W3C中定义事件的发生经历三个阶段:捕获阶段(capturing)、目标阶段(targetin)、冒泡阶段(bubbling

  • 冒泡型事件:当你使用事件冒泡时,子级元素先触发,父级元素后触发
  • 捕获型事件:当你使用事件捕获时,父级元素先触发,子级元素后触发
  • DOM事件流:同时支持两种事件模型:捕获型事件和冒泡型事件
  • 阻止冒泡:在W3c中,使用stopPropagation()方法;在IE下设置cancelBubble = true
  • 阻止捕获:阻止事件的默认行为,例如click - 后的跳转。在W3c中,使用preventDefault()方法,在IE下设置window.event.returnValue = false

19.new操作符具体干了什么呢?

  • 创建一个空对象,并且 this 变量引用该对象,同时还继承了该函数的原型
  • 属性和方法被加入到 this 引用的对象中
  • 新创建的对象由 this 所引用,并且最后隐式的返回 this

20.JavaScript中执行上下文和执行栈是什么?

执行上下文: 是一种对Javascript代码执行环境的抽象概念,也就是说只要有Javascript代码运行,那么它就一定是运行在执行上下文中

  • 全局执行上下文:只有一个,浏览器中的全局对象就是 window对象,this 指向这个全局对象
  • 函数执行上下文:存在无数个,只有在函数被调用的时候才会被创建,每次调用函数都会创建一个新的执行上下文
  • Eval function execution context: refers to evalthe code running in the function, which is rarely used and not recommended

Execution stack: also called call stack, has a LIFO (last-in-first-out) structure for storing all execution contexts created during code execution

  • When Javascriptthe engine starts executing your first line of script code, it creates a global execution context and pushes it onto the execution stack
  • Whenever the engine encounters a function, it creates a function execution context and then pushes this execution context onto the execution stack
  • The engine will execute the execution context (usually the function execution context) at the top of the execution stack. When the function execution ends, the corresponding execution context will be popped up, and then the control flow will reach the next execution context of the execution stack.

21. What is the difference between typeof and instanceof?

typeofoperator returns a string representing the type of the unevaluated operand

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-GFG2mFwF-1686967105042) (C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\ 1683945877205.png)]

instanceofThe operator is used to detect whether the attribute of the constructor prototypeappears on the prototype chain of an instance object

the difference:

  • typeofWill return the basic type of a variable, instanceofand return a boolean value
  • instanceofCan accurately judge complex reference data types, but cannot correctly judge basic data types
  • And typeofthere are also disadvantages. Although it can judge the basic data type ( nullexcept), but in the reference data type, except for functionthe type, others cannot be judged

22. Five ways to judge whether it is an array?

  • instanceof data instanceof Array
  • constructor data.constructor == Array
  • Array.isArray()Array.isArray(data) most recommended
  • typeof typeof(data)
  • Object.prototype.toSrtring.call()

23. What are the methods to determine the type of a value?

  • typeof operator
  • instanceof operator
  • Object.prototype.toString.call 方法
  • constructor

24. ajax过程?

(1)创建XMLHttpRequest对象,也就是创建一个异步调用对象.
(2)创建一个新的HTTP请求,并指定该HTTP请求的方法、URL及验证信息.
(3)设置响应HTTP请求状态变化的函数.
(4)发送HTTP请求.
(5)获取异步调用返回的数据.
(6)使用JavaScript和DOM实现局部刷新.

25.Ajax原理,ajax优缺点?

  • Ajax的原理简单来说是在用户和服务器之间加了—个中间层(AJAX引擎),通过XmlHttpRequest对象来向服务器发异步请求,从服务器获得数据,然后用javascript来操作DOM而更新页面。使用户操作与服务器响应异步化。这其中最关键的一步就是从服务器获得请求数据

  • Ajax的过程只涉及JavaScriptXMLHttpRequestDOMXMLHttpRequestajax的核心机制

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tk5uFVRn-1686967105043)(C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\1683946428125.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-R52CumK9-1686967105044)(C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\1683946512993.png)]

  • 优点:
    • 通过异步模式,提升了用户体验.
    • 优化了浏览器和服务器之间的传输,减少不必要的数据往返,减少了带宽占用.
    • Ajax在客户端运行,承担了一部分本来由服务器承担的工作,减少了大用户量下的服务器负载。
    • Ajax可以实现动态不刷新(局部刷新)
  • 缺点:
    • 安全问题 AJAX暴露了与服务器交互的细节。
    • 对搜索引擎的支持比较弱。
    • 不容易调试。

26.bind、call、apply 区别?

bind、call、apply用来改变this指向

apply:接受两个参数,第一个参数是this的指向,第二个参数是函数接受的参数,以数组的形式传入

改变this指向后原函数会立即执行,且此方法只是临时改变this指向一次 fn.apply(null,[1,2,3]);

call: 第一个参数也是this的指向,后面传入的是一个参数列表 fn.call(obj,1,2,3)

bind: bind方法和call很相似,第一参数也是this的指向,后面传入的也是一个参数列表(但是这个参数列表可以分多次传入) 返回的是新的函数

27.如何实现一个bind?

实现bind三步:

  • 修改this指向
  • 动态传递参数
  • 兼容new关键字

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Au8o7qGB-1686967105045)(C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\1683947651751.png)]

28.说说你对正则表达式的理解?应用场景?

正则表达式是一种用来匹配字符串的强有力的武器

应用场景:

  • 验证QQ合法性(5~15位、全是数字、不以0开头):
  • 验证手机号格式

29.对事件循环的理解(详细)?

前提: JavaScript是一门单线程的语言,意味着同一时间内只能做一件事,但是这并不意味着单线程就是阻塞,而实现单线程非阻塞的方法就是事件循环

JavaScript中,所有的任务都可以分为

  • 同步任务:立即执行的任务,同步任务一般会直接进入到主线程中执行
  • 异步任务:异步执行的任务,比如ajax网络请求,setTimeout定时函数等

同步任务进入主线程,即主执行栈,异步任务进入任务队列,主线程内的任务执行完毕为空,会去任务队列读取对应的任务,推入主线程执行。上述过程的不断重复就事件循环

异步任务分为微任务宏任务:

微任务: 一个需要异步执行的函数,执行时机是在主函数执行结束之后、当前宏任务结束之前

  • Promise
  • MutaionObserver 监听dom发生改变的
  • Object.observe(已废弃;Proxy 对象替代)
  • process.nextTick(Node.js)

宏任务: 宏任务的时间粒度比较大,执行的时间间隔是不能精确控制的,对一些高实时性的需求就不太符合

  • script (可以理解为外层同步代码)
  • setTimeout/setInterval
  • postMessage、MessageChannel
  • setImmediate、I/O(Node.js)

执行顺序:

  • 先执行同步代码,
  • 遇到异步宏任务则将异步宏任务放入宏任务队列中,
  • 遇到异步微任务则将异步微任务放入微任务队列中,
  • 当所有同步代码执行完毕后,再将异步微任务从队列中调入主线程执行,
  • 微任务执行完毕后再将异步宏任务从队列中调入主线程执行,
  • 一直循环直至所有任务执行完毕。

30.DOM常见的操作有哪些?

  • 创建节点
    • createElement 创建新元素,接受一个参数,即要创建元素的标签名
  • 查询节点
    • querySelector 传入任何有效的css 选择器,即可选中单个 DOM元素(首个) 如果页面上没有指定的元素时,返回 null
    • querySelectorAll returns a list containing all matching Elementnodes in the node subtree, or an empty node list if there is no match
  • update node
    • innerHTML can not only modify DOMthe text content of a node, but also directly HTMLmodify DOMthe subtree inside the node through fragments
    • innerText
    • style dom object.style.style property = ''
  • add node
    • innerHTML
    • appendChild adds a child node to the last child node of the parent node
    • insertBefore (new dom, specified dom object) inserts the child node in front of the specified position
    • setAttribute adds an attribute node to the specified element, and changes the attribute value if the attribute already exists in the element
  • delete node
    • removeChild gets the parent node, the node dom object to be deleted. parent.removeChild(child)

31. Tell me about your understanding of BOM, what do you know about common BOM objects?

BOM(Browser Object Model), the browser object model, provides objects that interact with the browser window independently of the content.

The entire content of the browser can be viewed as DOM, and the entire browser can be viewed as BOM.

BOM object:

  • window: BomThe core object is windowthat it represents an instance of the browser. In the browser, windowan object has a dual role as an interface to the browser window and as a global object
  • location: get url address information
  • navigator: The object is mainly used to obtain the properties of the browser and distinguish the browser type
  • screen: What is saved is purely client capability information, that is, the information of the client display outside the browser window, such as pixel width and pixel height
  • URLhistory: Mainly used to operate the history of the browser , you can pass parameters forward, backward, or to the specified URLjump

32. What is the difference between BOM and DOM?

  • BOM (Browser Object): methods and objects that interact with the browser
    • BOM is the browser object model, it refers to 将浏览器当作一个对象treat, this object mainly defines the methods and interfaces to interact with the browser
    • The core of the BOM is the window, and the window object has a dual role. It is not only an interface for js to access the browser window, but also a global object (Global)
    • This means that any object, variable and function defined in the web page will exist as a property or method of the global object
  • DOM (Document Object Model): methods and interfaces for processing web content
    • DOM is the Document Object Model, which refers to treating a document as an object, which mainly defines the content and interface for processing web pages

33. How to solve the cross-domain problem?

Understand the same-origin policy: The same-origin means that " protocol + domain name + port " are the same. It is the core and most basic security function of the browser. If the same-origin policy is missing, the browser is vulnerable to XSSattacks CSRFsuch as .

  • Cross-domain through jsonp
  • nginx proxy cross-domain
  • nodejs middleware cross-domain
  • The backend sets the security domain name in the header information
  • front proxy

34. How to load js asynchronously?

  • Set the ``property async="async"(once the script is available, it will be executed asynchronously)
  • Create dynamically script DOM:document.createElement('script');
  • XmlHttpRequestscript injection
  • Load libraries asynchronouslyLABjs
  • module loaderSea.js

35. Which operations will cause memory leaks?

Memory leak: JavaScript memory leak means that the object still exists when it is not needed to use it, so the occupied memory cannot be used or recycled

  • varglobal variable not declared with
  • closure function ( Closures)
  • Circular reference (two objects refer to each other)
  • console log ( console.log)
  • DOMRemove elements that have bound events ( IE)
  • setTimeoutUsing a string as the first parameter instead of a function will cause a memory leak
  • 垃圾回收器定期扫描对象,并计算引用了每个对象的其他对象的数量。如果一个对象的引用数量为 0(没有其他对象引用过该对象),或对该对象的惟一引用是循环的,那么该对象的内存即可回收

36.XML和JSON的区别?

  • 数据体积:JSON数据体积更小
  • 数据交互:JSON与JavaScript得交互更加方便,更容易被解析,更好的数据传输
  • 传输速度:JSON传输速度快
  • 数据描述:JSON对数据的描述相比XML较差

37.说说你对递归得理解?

递归: 在数学与计算机科学中,是指在函数的定义中使用函数自身的方法

38.说说你对函数式编程的理解?优缺点?纯函数,高阶函数,柯里化

主要的编程范式有三种:命令式编程,声明式编程和函数式编程

函数式编程: 更加强调程序执行的结果而非执行的过程,简单来讲,就是要把过程逻辑写成函数,定义好输入参数,只关心它的输出结果

纯函数: 纯函数是对给定的输入返还相同输出的函数,并且要求你所有的数据都是不可变的,即纯函数=无状态+数据不可变

  • 函数内部传入指定的值,就会返回确定唯一的值
  • 不会造成超出作用域的变化,例如修改全局变量或引用传递的参数

高阶函数: 是以函数作为输入或者输出的函数被称为高阶函数

柯里化: 把一个多参数函数转化成一个嵌套的一元函数的过程

优点:

  • 更好的管理状态
  • 更简单的复用
  • 减少代码量,提高维护性

缺点:

  • 性能:函数式编程相对于指令式编程,性能绝对是一个短板,因为它往往会对一个方法进行过度包装,从而产生上下文切换的性能开销
  • 资源占用:在 JS 中为了实现对象状态的不可变,往往会创建新的对象,因此,它对垃圾回收所产生的压力远远超过其他编程方式
  • 递归陷阱:在函数式编程中,为了实现迭代,通常会采用递归操作

39.Javascript中如何实现函数缓存?函数缓存有哪些应用场景?

函数缓存,就是将函数运算过的结果进行缓存

实现方式: 实现函数缓存主要依靠闭包、柯里化、高阶函数

应用场景:

  • 对于昂贵的函数调用,执行复杂计算的函数
  • 对于具有有限且高度重复输入范围的函数
  • 对于具有重复输入值的递归函数
  • 对于纯函数,即每次使用特定输入调用时返回相同输出的函数

40. JSON 的了解?

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。
它是基于JavaScript的一个子集。数据格式简单, 易于读写, 占用带宽小
{‘age’:‘12’, ‘name’:‘back’}

41. document.write 和 innerHTML 的区别?

document.write 只能重绘整个页面
innerHTML 可以重绘页面的一部分

42. 请解释一下 JavaScript 的同源策略?

概念:同源策略是客户端脚本(尤其是Netscape Navigator2.0,其目的是防止某个文档或脚本从多个不同源装载。
这里的同源策略指的是:协议,域名,端口相同,同源策略是一种安全协议。
指一段脚本只能读取来自同一来源的窗口和文档的属性。

43. 介绍一下闭包和闭包常用场景?

  • 闭包是指有权访问另一个函数作用域中的变量的函数,创建闭包常见方式,就是在一个函数的内部创建另一个函数
  • 使用闭包主要为了设计私有的方法和变量,闭包的优点是可以避免变量的污染,缺点是闭包会常驻内存,会增大内存使用量,使用不当很容易造成内存泄露。在js中,函数即闭包,只有函数才会产生作用域的概念。
  • 闭包有三个特性:
    • 函数内再嵌套函数
    • 内部函数可以引用外层的参数和变量
    • 参数和变量不会被垃圾回收机制回收
  • 闭包的好处: 能够实现封装和缓存等;
  • 闭包的缺点就是常驻内存,会增大内存使用量,使用不当会造成内存泄漏
  • 应用场景:
    • 常见的防抖节流
    • 使用闭包可以在 JavaScript 中模拟块级作用域
    • 闭包可以用于在对象中创建私有变量

44. javascript的内存(垃圾)回收机制?

  • The garbage collector will find out the memory that is no longer used every once in a while, and then release the memory for it
  • Mark and sweep method (mark and sweep) ,
    • This is the most common garbage collection method in JavaScript. When a variable enters the execution environment, such as a variable declared in a function, the garbage collector marks it as "entering the environment". Marked as "leaving the environment"
    • The garbage collector will mark all the variables stored in memory at runtime, and then remove the variables in the environment and the variables (closures) referenced by the variables in the environment. The deleted variable
  • reference counting
    • Memory leaks often occur in lower versions of IE, and many times it is because it uses reference counting for garbage collection. The strategy of reference counting is to track and record the number of times each value is used. When a variable is declared and a reference type is assigned to the variable, the number of references to the value is increased by 1. If the value of the variable becomes another , then the number of references to this value is reduced by 1. When the number of references to this value becomes 0, it means that there is no variable in use, and this value cannot be accessed. Therefore, the space it occupies can be reclaimed, so that the garbage collector will be in the When running, clean up the space occupied by the value whose reference count is 0.
  • In IE, although JavaScript objects are garbage collected by marking and clearing, BOM and DOM objects are garbage collected by reference counting, which means that as long as BOM and DOM are involved, circular reference problems will occur.

45. Write the sum of 1 to 100 in js recursively?

function add(num1, num2) {
	const num = num1 + num2;
    if(num2 === 100) {
        return num;
	} else {
	    return add(num, num2 + 1)
    }
}
var sum = add(1, 2);              

46. ​​Event queue (macro task micro task)

Can be divided into micro task (micro task) queue and macro task (macro task) queue.

Microtasks are generally executed before macrotasks, and there is only one microtask queue, and there may be multiple macrotask queues . In addition, our common click and keyboard events also belong to macro tasks.

Let's take a look at common macro tasks and common micro tasks.

Common macro tasks:

  • setTimeout()
  • setInterval()
  • setImmediate()

Common microtasks:

  • promise.then()、promise.catch()
  • new MutaionObserver()
  • process.nextTick()

微任务和宏任务的本质区别。

  • 宏任务特征:有明确的异步任务需要执行和回调;需要其他异步线程支持。
  • 微任务特征:没有明确的异步任务需要执行,只有回调;不需要其他异步线程支持。
setTimeout(function () {
    console.log("1");
}, 0);
async function async1() {
    console.log("2");
    const data = await async2();
    console.log("3");
    return data;
}
async function async2() {
    return new Promise((resolve) => {
        console.log("4");
        resolve("async2的结果");
    }).then((data) => {
        console.log("5");
        return data;
    });
}
async1().then((data) => {
    console.log("6");
    console.log(data);
});
new Promise(function (resolve) {
    console.log("7");
  resolve()
}).then(function () {
    console.log("8");
});

// 2 4 7 5 8 3 6 async2的结果 1

43.async/await, Generator

async 是一个通过异步执行并隐式返回 Promise 作为结果的函数。是Generator函数的语法糖,并对Generator函数进行了改进。
改进:

  • 内置执行器,无需手动执行 next() 方法。
  • 更好的语义
  • 更广的适用性:co模块约定,yield命令后面只能是 Thunk 函数或 Promise 对象,而async函数的await命令后面,可以是 Promise 对象和原始类型的值(数值、字符串和布尔值,但这时会自动转成立即 resolved 的 Promise 对象)。
  • 返回值是 Promise,比 Generator 函数返回的 Iterator 对象方便,可以直接使用 then() 方法进行调用。
  • async 隐式返回 Promise 作为结果的函数,那么可以简单理解为,await后面的函数执行完毕时,await会产生一个微任务(Promise.then是微任务)。

Generator 是 ES6 引入的新概念,它允许在函数执行过程中暂停和恢复它们的状态。通过 function* 声明一个 Generator 函数,可以在函数体内使用关键字 yield 来生成一个状态,并将函数挂起,等待下一次调用。Generator 函数返回一个可迭代对象,可以通过 next() 方法获取当前生成器的状态值。使用 Generator 函数可以更简单地实现异步操作,避免回调嵌套带来的问题。

48. JavaScript 是单线程的,浏览器是多进程的

  • 每打开一个新网页就会创建一个渲染进程
  • The rendering process is multi-threaded
  • GUI rendering thread responsible for page rendering
  • The JavaScript engine thread responsible for the execution of JavaScript
  • The event-triggered thread responsible for the browser's event loop, note that this is not part of the JavaScript engine thread management
  • The timing trigger thread responsible for the timer, the time interval below 4ms in setTimeout is counted as 4ms
  • Asynchronous http request thread responsible for XMLHttpRequest
  • GUI rendering thread and JavaScript engine thread are mutually exclusive
  • Single-threaded JavaScript is to avoid DOM rendering conflicts. Web workers support multi-threading, but web workers cannot access window objects, document objects, etc.

49. Talk about the problem of loss of precision in Javascript numbers, how to solve it?

Example: 0.1+0.2===0.3 =>false involves IEE754 standard

problem causes:

  • To store double-precision floating-point numbers, the computer needs to first convert the decimal number to binary scientific notation, and then the computer uses its own rules {sign bit + (exponent bit + binary offset of the exponent) + decimal part} to store the binary scientific notation
  • Because there is a limit on the number of digits (64 bits) when storing, and some decimal floating-point numbers will appear infinite loops when converted to binary numbers, which will cause binary rounding operations (0 rounding 1), when converted to decimal cause calculation error

solve:

  • Use the toFixed() method: convert the floating-point number to a string form of a specified number of decimals
  • Using third-party libraries, Math.js,BigDecimal.js

50. Tell me about your understanding of modular solutions, such as what are CommonJS, AMD, CMD, and ES Module?

  • CommonJS loads module synchronization, mainly used on the server side, it mainly relies on require and exports to achieve modularization, require users to load modules, and exports is used to export modules
  • AMD asynchronous module definition, which solves the problem of file management and module loading in the browser environment. Unlike commonjs, AMD loads modules asynchronously
  • CMD general module definition, cmd is also to solve the browser-side modularization, and AMD is different in that it uses a synchronous way to load modules, mainly relying on require and define to achieve modularization
  • ES Module是es6新增的模块化方案,支持在浏览器和node.js使用,并且已经得到了嵌入式运行环境的支持,与commonjs和amd不同,ES Module是静态加载它使用import和export关键字实现模块化

51.用过哪些设计模式?

  • 工厂模式:
    • 工厂模式解决了重复实例化的问题,但还有一个问题,那就是识别问题
    • 主要好处就是可以消除对象间的耦合,通过使用工程方法而不是new关键字
  • 构造函数模式
    • 使用构造函数的方法,即解决了重复实例化的问题,又解决了对象识别的问题,该模式与工厂模式的不同之处在于,直接将属性和方法赋值给 this对象;

52.javascript有哪些方法定义对象?

  • 对象字面量: var obj = {}; 原型是Object.prototype
  • 构造函数: var obj = new Object();
  • Object.create(): var obj = Object.create(Object.prototype);

53.说说你对promise的了解

54.web开发中会话跟踪的方法有哪些?

  • cookie
  • session
  • url重写
  • 隐藏input
  • ip地址

55.介绍js有哪些内置对象?

  • ObjectJavaScript 中所有对象的父对象
  • 数据封装类对象:ObjectArrayBooleanNumberString
  • 其他对象:FunctionArgumentsMathDateRegExpError

56.eval是做什么的?

  • 它的功能是把对应的字符串解析成JS代码并运行
  • 应该避免使用eval,不安全,非常耗性能(2次,一次解析成js语句,一次执行)
  • JSON字符串转换为JSON对象的时候可以用eval,var obj =eval('('+ str +')')

57.parseInt函数,[“1”, “2”, “3”].map(parseInt) 答案是多少?

parseInt函数接收两个参数第一个参数是要被解析的字符串,第二个参数是一个可选的进制数。

答案:【1,NaN,NaN】

解析:

  • [‘1’,‘2’,‘3’].map(parseInt)通过map便利的数组会将索引作为第二个参数传入,所以会以parseint(2,1)第二个参数1不是合法的进制数,paeseint(3,2)这里因为3不是二进制数

58.javascript 代码中的"use strict";是什么意思?说说严格模式的限制

  • use strict是一种ECMAscript 5 添加的(严格)运行模式,这种模式使得 Javascript 在更严格的条件下运行,使JS编码更加规范化的模式,消除Javascript语法的一些不合理、不严谨之处,减少一些怪异行为

限制:

  • 变量必须声明后再使用
  • 函数的参数不能有同名属性
  • 不能使用with语句
  • 禁止this指向window

59.js延迟加载的方式有哪些?

  • 设置``属性 defer="defer" (脚本将在页面完成解析时执行)
  • 动态创建 script DOMdocument.createElement('script');
  • XmlHttpRequest 脚本注入
  • 延迟加载工具 LazyLoad

60.同步和异步的区别?

  • 同步:浏览器访问服务器请求,用户看得到页面刷新,重新发请求,等请求完,页面刷新,新内容出现,用户看到新内容,进行下一步操作
  • 异步:浏览器访问服务器请求,用户正常操作,浏览器后端进行请求。等请求完,页面不刷新,新内容也会出现,用户看到新内容

61.ES6新特性

  • 增加了letconst命令,用来声明变量。
  • 新增模板字符串(为JavaScript提供了简单的字符串插值功能)
  • 箭头函数
  • for-of(用来遍历数据—例如数组中的值。)
  • arguments对象可被不定参数和默认参数完美代替。
  • 扩展运算符,解构赋值
  • ES6promise对象纳入规范,提供了原生的Promise对象。
  • Added block-level scope, letthe command actually increases the block-level scope.
  • There is also the concept of introducing modulemodules
  • Generator generator
  • Classes and Inheritance

62. What is the difference between let, const, and var?

通过const声明的对象属性不可修改!!!

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-nUkDO8Ka-1686967105046) (C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\ 1684154487983.png)]

63. What is the difference between let and var?

  • letThere is no variable promotion in the command, if it is used letbefore , it will cause an error
  • If there are letand constcommands in the block area, it will form an enclosing scope
  • Duplicate declarations are not allowed, therefore, parameters cannot be redeclared inside a function

64. What happens if new is an arrow function?

The arrow function was proposed in ES6. It has no prototype, and it does not have its own this pointer, and it cannot use the arguments parameter, so a new arrow function cannot be created.

65. What is the difference between an arrow function and an ordinary function?

  • Arrow functions are more concise than ordinary functions
  • Arrow functions do not have their own this
  • The this inherited by the arrow function will never change
  • Arrow functions cannot be used as constructors
  • Arrow functions have no arguments
  • call, bind, apply cannot change the point of this

66. The role of the spread operator

Spread operator: (…)

Object extension operator: used to take out all traversable properties in the parameter object and copy them to the current object

Array expansion operator: an array can be converted into a sequence of parameters separated by commas, and only one layer of array can be expanded at a time

67. Template syntax and string processing in ES6

Before es6, strings were spliced ​​using '+' splicing, which is very troublesome

es6 character template use: `` combined with ${variable name}

var name='lc'
var age = 27
var address = 'zg'
var information = `my name ${name},I am ${age} years old this year,I'm from ${address}`

68. The difference between map and forEach

  • forEachThe method is the most basic method, which is traversal and looping. There are 3 parameters by default: the array content to be traversed item, the array index index, and the current array to be traversed Array. The original array will not be changed.
  • mapmethod, the basic usage is forEachthe same, but different, it will return a new array, so there needs to be returna value in the callback, if not, it will returnundefined

69. The difference between Js animation and CSS animation and the corresponding implementation

  • Advantages of CSS3 Animations
    • It will be slightly better in performance, and the browser will CSS3do some optimization for the animation
    • The code is relatively simple
  • shortcoming
    • Not flexible enough in animation control
    • poor compatibility
  • JavaScriptThe animation just makes up for these two shortcomings. It has a strong control ability and can be controlled and transformed in a single frame. At the same time, it is well written and fully compatible IE6, and it has powerful functions. For some animations with complex controls, javascriptit will be more reliable to use. When implementing some small interactive effects, think more about it CSS.

70. What is gulp?

  • gulpIt is a stream-based code construction tool in the front-end development process and a powerful tool for building automation projects; it can not only optimize website resources, but also many repetitive tasks can be automatically completed with the correct tools during the development process
  • Features of Gulp:
    • Ease of use : With a code-over-config strategy, gulp makes simple tasks simple and complex tasks manageable
    • Build fast Leveraging Node.jsthe power of streams, you can quickly build projects and reduce frequent IOoperations
    • Easy to learnAPI Master with minimal gulpeffort Effortless to build: as a series of streaming pipelines

71. The various stages of the event, addEventListener

capture phase – target phase – bubbling phase

  • Thus, the difference between setting the third parameter of addEventListener to true and false is very clear
    • true表示该元素在事件的“捕获阶段”(由外往内传递时)响应事件
    • false表示该元素在事件的“冒泡阶段”(由内向外传递时)响应事件 默认false

72.数组some函数和every函数

every 函数接受一个函数作为参数,这个函数会被依次应用到数组中的每个元素。该函数应该返回一个布尔值:

  • 如果返回 true,则表示当前元素满足条件,继续检查下一个元素。
  • 如果返回 false,则表示当前元素不满足条件,every 函数将立即返回 false,不再检查后面的元素

some 函数接受一个函数作为参数,这个函数会被依次应用到数组中的每个元素。该函数应该返回一个布尔值:

  • 如果返回 true,则表示当前元素满足条件,some 函数将立即返回 true,不再检查后面的元素。
  • 如果返回 false,则表示当前元素不满足条件,继续检查下一个元素。

73.数组乱序

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    arr.sort(() => Math.random() - 0.5)

74.如何渲染几万条数据并不卡住界面,requestAnimationFrame

requestAnimationFrame 是一个由浏览器提供的 API,用于优化页面动画、避免出现卡顿、异闻和掉帧的情况。它能够在浏览器下一次重绘之前,通知浏览器调用一个指定的函数来更新动画,从而使得动画呈现更加流畅、自然。

实现流程:假如有一万条数据,我们还需要设置每次渲染条数,总计渲染次数,当前渲染次数三个变量。首先自动执行一次渲染函数(loop),通过条件判断当前渲染次数是否小于总渲染次数进行继续执行,满足条件调用window.requestAnimationFrame(具体渲染函数add);add函数中创建空标签用来接收每次渲染的结构,减少回流次数,当前渲染次数+1,继续执行loop函数

// 插入十万条数据
        const total = 100000
        // 一次插入 20 条,如果觉得性能不好就减少
        const once = 20
        // 渲染数据总共需要几次
        const loopCount = total / once
        // 当前渲染次数
        let countOfRender = 0
        let ul = document.querySelector("ul");
        function add() {
    
    
            // 优化性能,插入不会造成回流  createDocumentFragment是一个指向空DocumentFragment对象的引用。下面先将20条插入空元素避免回流
            const fragment = document.createDocumentFragment();
            for (let i = 0; i < once; i++) {
    
    
                const li = document.createElement("li");
                li.innerText = Math.floor(Math.random() * total);
                fragment.appendChild(li);
            }
            // 一次性添加dom,减少回流次数
            ul.appendChild(fragment);
            countOfRender += 1;  
            loop();
        }
        function loop() {
    
    
            if (countOfRender < loopCount) {
    
    
                window.requestAnimationFrame(add);
            }
        }
        loop();

75.获取到页面中所有的checkbox怎么做

 var domList = document.getElementsByTagName(‘input’)
 var checkBoxList = [];
 var len = domList.length;  //缓存到局部变量
 while (len--) {
    
      //使用while的效率会比for循环更高
   if (domList[len].type == ‘checkbox’) {
    
    
       checkBoxList.push(domList[len]);、
   }
 }

76.怎样添加、移除、移动、复制、创建和查找节点

创建节点:

  • createElement() 创建一个具体元素
  • createDocumentFragment() 创建一个dom片段
  • createTextNode() 创建一个文本节点

Add, remove, replace, insert:

  • appendChild() adds
  • removeChild() removes
  • replaceChild() replaces
  • insertBefore() Insert

Find:

  • getElementsByTagName() //By tag name
  • getElementsByName() // Pass the value of the Name attribute of the element
  • getElementById() //By element Id, uniqueness

77.window.onload和$(document).ready

  • window.onload()The method is to wait until all the elements including pictures in the page are loaded before it can be executed.
  • $(document).ready()It is DOMexecuted after the structure is drawn, and there is no need to wait until the loading is complete

78. The difference between addEventListener() and attachEvent()

  • addEventListener()It is a standard method that complies with the W3C specification; attachEvent()it is a non-standard method for lower versions of IE
  • addEventListener()Support event bubbling and event capture; - and attachEvent()only support event bubbling
  • addEventListener()In the first parameter of , the event type does not need to be added on; attachEvent()it needs to be added'on'
  • If multiple events are bound to the same element, addEventListener()they will be executed sequentially according to the order of event binding, and attachEvent()will be executed in reverse order according to the order of event binding

79. Array deduplication

Use ES6 Set to remove duplicates (most commonly used in ES6)

var arr = [1,2,2,2,3,3,3,3];

console.log(new Set(arr))

traversal deduplication

include,indexof

80. Determine if two objects are equal

Normally, through == comparison, it is not possible to judge whether the objects are equal

It needs to be converted to a string first through JSON.stringify() and then compared

81. Anti-shake throttling

Throttling: If this event will be triggered frequently, the throttling function will execute the function according to a certain number 频率, no matter how many times this event is triggered in the middle, the frequency of executing the function is always fixed;

Anti-shake: When an event is triggered, the corresponding function will not be triggered immediately, but will be triggered 等待一定的时间(very short time). When the event is triggered intensively, the triggering of the function will be frequently delayed, and only after waiting for a period of time, there will be no event Triggered, the response function will actually be executed

82. What are the ways to detect the browser version?

  • according tonavigator.userAgent UA.toLowerCase().indexOf('chrome')
  • According to windowthe member of the object'ActiveXObject' in window

83. Basic specification of javascript

  • Do not declare multiple variables on the same line
  • Please use ===/!==to compare true/falseor numerical
  • Use an object literal instead of new Arraythis form
  • Do not use global functions
  • Switchstatement must have defaulta branch
  • IfStatements must use curly braces
  • for-inVariables in loops should be letexplicitly scoped using keywords to avoid scope pollution

84. What are the advantages of npm and yarn, pnpm

npm:

  • npm is the package manager that comes with Node.js, so there is no need to install additional packages when using npm, and you can use a large number of third-party packages. The commands of npm are easy to learn and can meet the needs of most projects.

yarn :

  • Provides better performance and speed, and can download in parallel when installing packages, thus improving the efficiency of installation
  • The concept of lock files is introduced to ensure the consistency of package versions in the development environment and production environment, thus avoiding problems caused by incompatible package versions.
  • Supports offline mode. If the required packages are already installed in the project, yarn does not need to download packages from the Internet, but directly uses the packages in the local cache.

pnpm:

  • The biggest advantage is to save disk space pnpm only installs one package in the project
  • pnpm does not need to reinstall all dependencies, but incrementally installs each project and dependency

85. What are the reasons for the long loading time of the page and how to optimize it?

reason:

  • A large number of HTTP requests: During the page loading process, the browser needs to request the server to obtain resources such as HTML, CSS, JavaScript, and pictures of the page. If there are too many requests, the page loading time will become longer. Loading speed can be optimized by reducing the number of HTTP requests, such as combining CSS and JavaScript files, compressing images, etc.
  • Large amount of JavaScript code: When the browser downloads and parses the JavaScript code, the rendering of the page will be blocked, which will also cause the page to load longer. You can optimize loading speed by loading JavaScript code asynchronously, lazy loading, or splitting it into multiple smaller files.
  • A lot of CSS code: Similar to JavaScript, CSS code will also block page rendering. You can optimize the loading speed by compressing CSS code, reducing the size and number of CSS files, and using external links.
  • Long server response time: If the server takes too long to respond, it can also cause the page to take longer to load. Server response time can be reduced by upgrading server hardware, optimizing code, etc.
  • Unreasonable DOM structure: If the DOM structure of the page is not reasonable, it will also cause the page to load longer. You can optimize the loading speed by reducing the number of DOM nodes, avoiding the use of table layout, and using CSS Sprite (Sprite).

optimization:

  • Compress HTML, CSS, JavaScript, images and other resources to reduce file size.
  • Combine CSS and JavaScript files to reduce the number of HTTP requests.
  • Load JavaScript code asynchronously, lazy load, or split into multiple smaller files.
  • Use browser cache to avoid repeated downloads of resources.
  • Use external links or CDN accelerators to speed up resource loading.
  • Reduce the number of DOM nodes and avoid using table layout to optimize page rendering speed.

86. DOM clone operation

Deep clone (text node in the cloned element plus all descendant element nodes),

Shallow clone (cloning the element itself, not cloning text nodes and descendant nodes)

cloneNode() accepts a parameter that can optionally be true or false. True to clone the element and all its child nodes. False means clone the element without including its child nodes

87. Sandbox mode

Sandbox mode is a software design pattern used to create an isolated, protected execution environment, isolate code from interacting with the outside world, and limit the resources and functions that code can access. In JavaScript, sandbox mode is usually implemented by encapsulating code in an anonymous function and calling it immediately. This creates a private scope in which variables do not leak into the global scope, avoiding variable name collisions and data pollution.

Although closures and sandbox patterns are different concepts, they can be combined with each other to achieve higher-level programming needs. For example, closures can be used to create a sandbox that limits the scope of variables a function can access. This combination results in cleaner, safer, and easier-to-maintain code.

88. What is the difference between string and tostring

The difference between the string and ToString methods is that they do different things.

string is a data type used to store and manipulate strings and ToString is a generic method used to convert data into strings. When we need to convert some non-string type data to a string, we can use the ToString method to achieve it.

toString takes one parameter. Can convert numeric strings into corresponding base numbers

string可以将任何数据类型转化为字符串,toString不可以转换null和undefined

89.js data storage method

  • Cookie: Cookie is a mechanism for storing data on the browser side, which can support long-term storage of data, and data can be shared between different pages. Cookies can be manipulated using JavaScript through the document.cookie property.
  • Web Storage: Web Storage provides two mechanisms, Session Storage and Local Storage, both of which are new to HTML5. Session Storage is used for temporary session data storage, and the data will be cleared after the user closes the browser, while Local Storage can store the data for a long time, even if the user closes the browser, it will not be lost. These two storage mechanisms can be manipulated through the window.sessionStorage and window.localStorage objects using JavaScript.
  • IndexedDB: IndexedDB is a mechanism for storing large amounts of structured data in the browser, which is similar to a local database. IndexedDB provides an asynchronous API that can create an object storage space in the browser and store key-value pair data in it. This storage mechanism can be manipulated through the IndexedDB API using JavaScript.
  • Web SQL: obsolete

90.cookie, session, token difference

  • Cookie: Cookie is a mechanism for storing data on the user side, which can store some simple user information and identification. The server sets a cookie and sends it to the client, and the client will automatically carry the cookie in the next request, so as to verify the user's identity or perform other operations. The disadvantage of cookies is that they may face security problems, because cookies are stored on the client side and are vulnerable to theft or forgery attacks.
  • Session: Session is a mechanism for storing data on the server side, which can save some complex user information and status, and is used to verify and track user identities. The server uses a unique Session ID to interact with the client, thus avoiding security issues. However, Session also has some disadvantages, such as greater pressure on the server load.
  • Token: Token is an encrypted string containing user identity and permission information, usually generated by the server and sent to the client. The client uses Token instead of Cookie or Session for authentication and data transmission. The advantage of Token is that it can reduce server pressure, reduce network traffic and delay, and reduce security issues. The disadvantage of Token is that it needs to ensure the security of its encryption and transmission.

Cookie is suitable for simple authentication and data storage, Session is suitable for scenarios that require complex state management and user tracking, and Token is more suitable for cross-platform data transmission such as distributed systems and APP.

91.js convert decimal to binary

  • Using toString()method and parameter 2:
let num = 123
num.toString()  //'123'
num.toString(2)  //'1111011'

92. How to make multiple asynchronous functions execute sequentially

  • Use the method Promiseof thento chain asynchronous tasks.

  • Use async/awaitthe keyword.

93.settimeout event mechanism

setTimeout()The implementation of the method is based on the event mechanism, which will add the callback function to the event queue. When the specified delay time arrives, the callback function is pushed to the end of the event queue and waits for execution when the JavaScript engine is idle.

Due to JavaScript's single-threaded nature and event loop mechanism, multiple tasks may block the event queue, resulting in asynchronous code that cannot be executed in the expected order. We need to use timers reasonably to avoid this situation.

If the set delay time is less than 4 milliseconds, the actual delay time may be greater than the set value, because browsers usually use the minimum time interval of 4 milliseconds to execute timer tasks.

94. Bind binds multiple times in a row and finally points to this

Look at the code first:

function say() {
     
     
	alert(this.x);
};
var a = say.bind({
     
     x: 1});
var b = a.bind({
     
     x: 2});
b(); // 这里会输出1还是2呢?    答案:1

No matter how many times you use bind to bind, the final value of this of the original function is determined by the parameters passed in the first binding.

95. mep and set

  • Map: An iterable collection where each element consists of a key and a corresponding value. MapThe keys in can be of any type, and the values ​​can be of any type, including object references and primitive values.
  • Set: A collection containing only unique values, no duplicates are allowed. SetValues ​​in can be of any type, including object references and primitive values.

96. Large file upload

  1. Partial upload: divide a large file into multiple small files, upload each small file separately, and finally perform a merge operation on the server side, which can reduce the upload and download time, and once the upload fails, only the failed part needs to be re-uploaded , without re-uploading the entire file.
  2. Breakpoint resume upload: On the basis of fragment upload, you can use local storage technology to record the uploaded fragment information. When the upload fails, you can continue to upload the failed fragment according to the uploaded fragment information, so as to realize http.
  3. Streaming upload: In the traditional uploading method, the file needs to be completely read into the memory before uploading, while in the streaming uploading, the file is read and uploaded one by one according to the streaming method, which can avoid reading the entire large file at one time, thereby reducing memory usage.
  4. Compression upload: For certain file types, such as text files, pictures, videos, etc., you can compress them before uploading, which can reduce the file size and speed up the upload speed.
  5. Use SDK for resuming upload after power failure: In addition to realizing resumable upload by yourself, you can also use some third-party resumable upload SDKs, such as Qiniu and Alibaba Cloud, which provide related SDKs, which can simplify the implementation of large file uploads .

97. The solution to the 300 millisecond click delay of the mobile terminal Click

Cause: The browser needs to wait for a while (about 300 milliseconds) to detect whether the user has clicked or double-clicked.

  • 使用 FastClick:FastClick 是一个 JavaScript 插件,它可以通过消除移动浏览器上的点击延迟来提高 Web 应用程序的响应速度。使用 FastClick 只需要在页面加载完成后引入库文件,并在需要绑定快速点击的元素上通过 FastClick.attach(element) 方法进行绑定即可。
  • 使用 touch 事件:如果不想使用第三方库或插件,也可以通过原生的 touch 事件来模拟快速点击。例如,可以通过监听 touchstart 事件来代替 click 事件,实现更快的响应速度。
  • 设置 meta 标签:将以下 meta 标签添加到 HTML 文件的 head 标签中,可以告诉浏览器不要缩放页面,并且禁用缩放手势,从而提高点击响应速度:

98.如何判断一个对象为空对象

通过 Object.keys(obj) 方法获取对象的所有属性名,并判断属性数量是否为 0 来实现 、

let obj = {
     
     'name':'zs'}
Object.keys(obj).length     //1
let objs = {
     
     }
Object.keys(objs).length	//0

99.数组常用方法

  • push:向数组末尾添加一个或多个元素,并返回新的长度。
  • pop:删除并返回数组最后一个元素。
  • shift:删除并返回数组第一个元素。
  • unshift:向数组开头添加一个或多个元素,并返回新的长度。
  • concat:合并两个或多个数组,并返回新的数组。不改变原数组。
  • join:将数组中的所有元素转化为字符串,并用指定的分隔符连接起来。
  • slice:返回数组的一个片段(浅拷贝),不影响原数组。
  • splice:在数组中添加或删除元素,可修改原数组。
  • sort:对数组元素进行排序,默认按照 Unicode 码点升序排列,可传入回调函数实现自定义排序。
  • reverse:翻转数组元素顺序,改变原数组。
  • indexOf:查询元素在数组中第一次出现的位置,找到返回其下标,否则返回-1。
  • lastIndexOf:从数组末尾开始查询元素在数组中最后一次出现的位置,找到返回其下标,否则返回-1。
  • filter:返回由满足回调函数条件的所有元素组成的新数组,不改变原数组。
  • map:返回一个新数组,其中的元素是对原有数组元素应用回调函数后得到的结果。
  • reduce: Accumulator method that executes a callback function for each element of the array (from left to right), returning a single value.
  • some: Determine whether the array has a value that satisfies the condition, and if so, return true
  • every: Determine whether all the values ​​of the array meet the conditions, and return true if they are all satisfied
  • forEach: loop array

100. Array Flattening

  • use recursion
  • Use the reduce method: The reduce method can be used to accumulate each element in the array into a result
  • Use the flat method:
    • The flat method of arrays was introduced in ES2019, which can flatten nested arrays into one-dimensional arrays.
    • The flat method can only reduce the number of nested layers to one dimension. If you need to flatten a multidimensional array into a one-dimensional array, you need to pass a parameter arr.flat( Infinity ) greater than or equal to the number of nested layers. Infinity means to flatten any deep nested arrays

101. The difference between for...in and for...of

The for...in loop is used to traverse object properties. It can enumerate all enumerable properties of the target object, including properties on the inheritance chain, but the order of traversal is uncertain

The for...of loop is used to traverse iterable objects (Iterable). It can traverse built-in iterable objects such as arrays, strings, Maps, and Sets, but it cannot traverse ordinary objects, nor can it traverse the properties of objects

the difference:

  • for...in traverses the array and returns the subscript, and traverses the object to return the key
  • for...of traverses the array to return data, and cannot traverse ordinary objects

102. Pseudo-array, convert pseudo-array to array

A pseudo-array is an array-like object that has an array-like structure and properties, but is not a real array.

In JavaScript, common pseudo-arrays include function parameters arguments, DOM element collections NodeListand HTMLCollectionetc.

The difference between pseudo-array and array:

  • Pseudo-arrays do not have array methods and attributes (such as push, pop, length), 不能使用数组相关的循环方法(such as forEach, map, reduce), etc. but they have an array-like structure,可以通过下标来访问元素,并且拥有 length 属性

Conversion: Array.from() method or spread operator

103. Two-dimensional array application scenarios

  • Game development: In game development, two-dimensional arrays are usually used to represent game scenes, maps, mazes, etc.
  • 图像处理: 在图像处理中,二维数组常用于表示图像的像素点,每个像素点可以用一个颜色值来表示
  • 数字计算: 在数学计算中,二维数组经常用于存储和处理矩阵

五、Vue 篇

1. 谈谈你对MVVM开发模式的理解?

MVVM是一种简化用户界面的实践驱动编程方式。在当前主流的前后端分离的开发模式中,MVVM模式的优越性日益体现,相较于经典的MVC模式,其对于程序模块的封装很好地解决了前后端信息交互的冗余和繁琐

MVVM分为Model、View、ViewModel三者。
Model 代表数据模型,数据和业务逻辑都在Model层中定义;
View 代表UI视图,负责数据的展示;
ViewModel 负责监听 Model 中数据的改变并且控制视图的更新,处理用户交互操作;
Model 和 View 并无直接关联,而是通过 ViewModel 来进行联系的,Model 和 ViewModel 之间有着双向数据绑定的联系。因此当 Model 中的数据改变时会触发 View 层的刷新,View 中由于用户交互操作而改变的数据也会在 Model 中同步。
这种模式实现了 Model 和 View 的数据自动同步,因此开发者只需要专注对数据的维护操作即可,而不需要自己操作 dom。

为什么使用MVVM:低耦合,可复用,独立开发,可测试

2. v-if 和 v-show 有什么区别?

  • 手段
    • v-if是动态的向DOM树内添加或者删除DOM元素;
    • v-show是通过设置DOM元素的display样式属性控制显隐;
  • 编译
    • v-if是惰性的,如果初始条件为假,则什么也不做;只有在条件第一次变为真时才开始局部编译;
    • v-show is compiled under any condition, regardless of whether the first condition is true or not, and then cached, and the DOM element is retained;
  • Performance consumption:
    • v-if has higher switching consumption;
    • v-show has a higher initial render cost
  • The v-if directive can be applied to the template wrapper element, v-show does not support it

3. route sum route sumThe difference between ro u t e and router

  • $route is a "routing information object", including routing information parameters such as path, params, hash, query, fullPath, matched, name, etc.
  • $router is a "routing instance" that wants to navigate to different URL objects, including routing jump methods, hook functions, etc. Use push, replace, go, back and other methods to realize the jump between pages

4.vue custom command

vue directive

vue2

局部注册:directive option

directives: {
    'focus': {
      bind(el, binding, vnode) {
        el.focus()
      }
    }
  }

全局注册:main.js

Vue.directives('focus',{
	bind(el, binding, vnode) {
        el.focus()
      }
})

生命周期

  • bind: Called only once, the instruction is bound to the element call for the first time for initialization
  • inserted: Called when the bound element is inserted into the parent node
  • update: the component vnode update call
  • componentUpdate: The command is called after all vnodes of the component and subcomponents have been updated
  • ubind: only one side is called, and the instruction is unbound

vue3

局部注册: Introduce import { Directive, DirectiveBinding } from 'vue' to check separately vFocus,binding

<template>
  <input type="text" v-focus="{ color: 'red' }" />
</template>

<script setup>
const vFocus = {
  created(el, binding) {
    el.style.backgroundColor = binding.value.color;
    console.log(el, binding.value.color); //<input type="text" style="background-color: red;"> 'red'
  },
};
</script>

全局注册: main.js, app.vue imported as above

import {
     
      createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)

app.directive('focus', {
     
     
    created(el, binding) {
     
     
        el.style.backgroundColor = binding.value.color;
        console.log(el, binding.value.color); //<input type="text" style="background-color: red;"> 'red'
    }
})

app.mount('#app')

生命周期

  • When the created element is initialized
  • The beforeMount directive is called only once after it is bound to the element
  • The mounted element is inserted into the parent dom call
  • beforeUpdate Called before the element is updated
  • update This periodic method is removed and replaced with updated
  • beforeUnmount is called before the element is removed
  • Called only once after the unmounted directive is removed

5. Vue project optimization

  • code level
    • Long list performance optimization: Object.freeze method to freeze an object, once the frozen object can no longer be modified
    • The event is destroyed, and the destruction logic is executed in the beforeDestroy lifecycle function.
    • Image lazy loading
    • Routing lazy loading
    • Load plugins on demand
    • v-if, v-for avoid using at the same time, v-for traversal to add key
    • v-if, v-show select
    • keep-alive component cache
    • input anti-shake throttling
  • Basic web technology optimization
    • Enable gzip compression
    • browser cache
    • CDN acceleration
  • webpack-optimization

6. How to compile the vue template

Vue's template compilation is the process of compiling "HTML" templates into render functions. This process can be roughly divided into three stages:

  • Parsing phase: parse the "HTML" template into an AST syntax tree;
    • Core parseHTML( template ,{}) Vue defines a lot of regular expressions that match HTML, parseHTML matches according to the regular
    • parseHTML is the "main thread" for parsing template strings. Its first parameter is the template string to be parsed, which is the outermost part of the single-file component; the second parameter is an option object, which Will contain some callbacks, and some configuration items.
    • options object:
      • start( tag, attrs, unary ) The callback when the start tag is matched, tag is the tag name of the current tag, attrs is the attribute list on the tag, and unary is whether the current tag is a self-closing tag
      • end() Callback when the end tag is matched
      • chars(text) callback for matching text nodes
      • comment(text) is matched to the callback of the comment node, and its processing logic is similar to that of text
  • Optimization stage: find out the static subtree from the AST syntax tree and mark it (the marked static subtree will be ignored during virtual dom comparison, thereby improving the performance of virtual dom comparison);
    • As briefly introduced above, the job of the optimization phase is to mark the static subtree. After marking the static subtree, there are two main advantages:
      • In the process of generating virtual dom, if a node is found to be a static subtree, a new subnode tree will not be generated except for the first rendering, but an existing static subtree will be copied;
      • In the process of comparing the virtual dom, if the current node is found to be a static subtree, skip it directly and do not need to compare.
    • The process of marking a static subtree is a two-step process:
      • Traverse the AST syntax tree, find all static nodes and mark them (Note: the current node and all its child nodes are static nodes, and the current node will be marked as a static node)
      • Traverse the tree after the above steps, find the static root node, and mark it (Note: The static root node refers to the node itself and all child nodes are static nodes, but the parent node is a dynamic node, and the static root node is also found. found the "static subtree")
  • Code generation stage: Generate code strings through AST, and finally generate render functions.

7. vue2 responsive principle

Vue uses several core components: Observer, Dep, Watcher,Scheduler

  • Observer converts an ordinary object into a responsive object
    • Observer converts each property of the object into a property with getter and setter through object.defineProperty
  • Dep means dependency. Vue will create a dep instance for each attribute in the responsive object, the object itself, and the array itself. Each dep instance can do two things:
    • Record dependency: who is using me
    • Distribution update: I have changed, I want to inform those who use me
  • During the execution of the watcher function, if a dependency record occurs, then dep will record this global variable, indicating that a watcher uses my attribute.
  • The Scheduler will not execute the update immediately, but update it asynchronously through nexttick

8. vue3 responsive principle

Through Proxy (proxy): Intercept the change of any attribute in the object, including: reading and writing of attribute values, adding attributes, deleting attributes, etc.

Through Reflect (reflection): operate on the properties of the source object, Reflect is not a function object, so it is not constructable.

9. After refreshing the browser, does the Vuex data exist? How to solve?

不存在

Reason: Because storethe data in is stored in the running memory, when the page is refreshed, the page will reload the vue instance, and the data in the store will be reassigned and initialized.

我们有两种方法解决该问题:

  1. 使用 vuex-along
  2. 使用 localStorage 或者 sessionStroage

10.vue和react共同点?区别

共同点:

  • 数据驱动视图
  • 组件化
  • 都使用 Virtual DOM

不同点

  • 核心思想不同
    • vue定位就是尽可能的降低前端开发的门槛,让更多的人能够更快地上手开发。这就有了vue的主要特点:灵活易用的渐进式框架,进行数据拦截/代理,它对侦测数据的变化更敏感、更精确
    • react 定位就是提出 UI 开发的新思路 React推崇函数式编程(纯组件),数据不可变以及单向数据流,当然需要双向的地方也可以手动实现, 比如借助onChangesetState来实现。
  • 组件写法
    • React推荐的做法是JSX + inline style, 也就是把 HTML 和 CSS 全都写进 JavaScript 中
    • Vue 推荐的做法是 template 的单文件组件格式(简单易懂,从传统前端转过来易于理解),即 html,css,JS 写在同一个文件(vue也支持JSX写法)
  • diff算法
  • 响应式原理
    • vue2采用object.defineProperty ,vue3采用proxy,reflect
    • React基于状态机,手动优化,数据不可变,需要setState驱动新的state替换老的state。

11.vue双向数据绑定原理

简易实现:v-model分为两部分,通过v-bind绑定值,再通过v-on:input来通步修改值

原理

  • 需要observe的数据对象进行递归遍历,包括子属性对象的属性,都加上setter和getter这样的话,给这个对象的某个值赋值,就会触发setter,那么就能监听到了数据变化
  • 通过dep来理清依赖关系,watcher在依赖中添加自身
  • compile解析模板指令,将模板中的变量替换成数据,然后初始化渲染页面视图,并将每个指令对应的节点绑定更新函数,添加监听数据的订阅者,一旦数据有变动,收到通知,更新视图
  • 待属性变动dep.notice()通知时,能调动watcher自身的update方法,并处罚compile回调渲染视图

12.computed和watch区别

computed计算属性,watch监听属性

  • 计算属性不在 data 中,它是基于data 或 props 中的数据通过计算得到的一个新值。watch 可以监听的数据来源:data,props,computed内的数据
  • component中有get和set方法,会默认缓存计算结果。watch不支持缓存,支持异步, immediate监听属性立即执行一次,deep开启深度监听

13.Vuex

Vuex是一种状态管理模式,存在的目的是共享可复用的组件状态。

主要包括以下几个模块:

  • State => 基本数据,定义了应用状态的数据结构,可以在这里设置默认的初始状态。
  • Getter => 从基本数据派生的数据,允许组件从 Store 中获取数据,mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性。
  • Mutation => 是唯一更改 store 中状态的方法,且必须是同步函数。
  • Action => 像一个装饰器,包裹mutations,使之可以异步。用于提交 mutation,而不是直接变更状态,可以包含任意异步操作。
  • Module => 模块化Vuex,允许将单一的 Store 拆分为多个 store 且同时保存在单一的状态树中。

14.vuex辅助函数

mapState, mapMutations, mapActions, mapGetters

mapState和mapGetters:

  • 两者都放在 computed中,以mapState举例
import { mapState } from 'vuex'

computed中
computed:{
	...mapState(['data'])  //data是vuex存放的state中的属性,此时{
    
    {data}}可使用
}

mapMutations, mapActions:

  • 放在组件的methods属性中 。使用与上类似

15.vuex模块化使用

当我们开发的项目比较大时,store中的数据就可能比较多,这时我们store中的数据就可能变得臃肿,为了解决这一问题,我们就需要将store模块化(module)

前提:创建两份js文件,含有属性与vuex写法相同,需要通过 namespaced:true开启命名空间store/index.js:在modules中引入文件

使用:

  • 访问state数据:
    • 第一种方式:this.$store.state.moduleA.sum
    • 第二种方式: ...mapState('moduleA',['sum','number'])
  • action提交mutation
  • 第一种方式:需要传参this.$store.dispatch('moduleB/addZhang',{name:'小明',age:18}) ,无需传参this.$store.dispatch('moduleB/addServer')
  • 第二种方式:...mapActions('moduleB',['addZhang'])
  • getters计算属性
  • 第一种方式: this.$store.getters['moduleB/firstName']
  • 第二种方式:...mapGetters('moduleB',['firstName'])

16.vue中mixin

mixin(混入): 提供了一种非常灵活的方式,来分发 Vue 组件中的可复用功能。

本质其实就是一个js对象,它可以包含我们组件中任意功能选项,如datacomponentsmethods createdcomputed等等

我们只要将共用的功能以对象的方式传入 mixins选项中,当组件使用 mixins对象时所有mixins对象的选项都将被混入该组件本身的选项中来

具体使用:

  • 创建mixins.js文件
let mixin = {
     
     
    created() {
     
     
        console.log('我是mixin中的');
    },
    methods: {
     
     
        hellow() {
     
     
            console.log('你好');
        },
    },
}
export default mixin
  • 局部使用
import mixin from "./mixins";
export default {
     
     
  mixins: [mixin],
  mounted() {
     
     
    this.hellow();//你好
  },
};
  • 全局使用main.js
import {
     
      createApp } from 'vue'
import App from './App.vue'
import mixins from "./mixins";
const app = createApp(App)
app.mixin(mixins)
app.mount('#app')

17.Vue中给对象添加新属性时,界面不刷新怎么办?

原因:vue2响应式采用object.defineProperty进行劫持,那个添加新属性时,新的属性不会具有get和set方法,不是一个响应式所以界面不刷新

解决:Vue.set() 向响应式对象中添加一个property,并确保这个新 property 同样是响应式的

vue3通过proxy劫持和reflect映射实现响应式,不会有这个问题

18.vue组件通讯方式

  • 通过 props 传递
    • props校验:name:{type:String,required:true,default:默认值} required是否必要
  • 通过 $emit 触发自定义事件
  • 使用 ref
  • EventBus
  • Provide 与 Inject
  • Vuex

19.vue3setup的父传子怎么去写?

介绍三种方法:

第一种:使用vue2写法通过props和$emit

第二种:setup函数写法

  • setup(props,context),通过props接收数据,通过context.emit(‘调用父组件方法’,传递参数)

第三种:script中setup

  • vue3自带defineProps,defineEmits
const emits = defineEmits(["changeNumber"]);
// 也可以不赋值,取值通过{
    
    {num}}获取
const props = defineProps({
  num: {
    type: Number,
    default: () => [],
  },
  list: {
    type: Array,
  },
});
const changeNum = function () {
  emits("changeNumber", 888);
  //   console.log(11111111111);
};

20.setup可不可以直接写async和await?

可以

setup 语法糖中可直接使用 await,不需要写 async , setup 会自动变成 async setup

<script setup>
  import Api from '../api/Api'
  const data = await Api.getData()
  console.log(data)
</script>

21.vue生命周期

vue2

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8P7sspQX-1686967105047)(C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\1685089235304.png)]

beforeCreate – 首次访问data

created – 首次访问this生命周期

mounted – 页面展示

vue3

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yfSFfojq-1686967105048)(C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\1685089301710.png)]

区别

  • beforeCreate -> setup() 开始创建组件之前,创建的是data和method
  • created -> setup()
  • beforeMount -> onBeforeMount 组件挂载到节点上之前执行的函数。
  • mounted -> onMounted 组件挂载完成后执行的函数
  • beforeUpdate -> onBeforeUpdate 组件更新之前执行的函数。
  • updated -> onUpdated 组件更新完成之后执行的函数。
  • beforeDestroy -> onBeforeUnmount 组件挂载到节点上之前执行的函数。
  • destroyed -> onUnmounted 组件卸载之前执行的函数。dszhuoyi
  • activated -> onActivated 组件卸载完成后执行的函数
  • deactivated -> onDeactivated

22.说说 Vue 中 CSS scoped 的原理

添加scoped标签后会给组件中所有标签元素,添加一个唯一标识,这个唯一标识就是自定义属性,data-v-xxxxxxxx这样的字眼,同时对应的样式选择器也会添加这个唯一的属性选择器

23.$nextTick原理

在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM

nextTick原理

24.data是函数不是对象

vue是一个单页面应用最终所有的实例都会挂载到app.vue文件,如果data是一个对象那么会导致数据污染。通过函数返回对象的方式,利用函数作用域的限制避免数据污染

25.路由守卫

vue路由守卫分为三种:全局路由守卫,独享路由守卫,组件路由守卫

to: 进入到哪个路由去

from: 来自哪个路由

next:是否跳转

  • 全局守卫: router.beforeEach((to,from,next)=>{})
  • 独享路由守卫: beforeEnter:(to,from,next)=>{}
  • 组件路由守卫: beforeRouteEnter:(to,from,next)=>{}, beforeRouteUpdate , beforeRouteLeave

26.vue设置全局变量

方法一:

  • vue2.xTo mount the global is Vue.prototype.$xxxx=xxxto mount in the form of , and then this.$xxxget the variables or methods mounted to the global through .
  • Vue 3In, use config.globalProperties, app.config.globalProperties.$data = '111'
 const {
     
     proxy} = getCurrentInstance()
 console.log(proxy.$data)

Method Two:

  • provide/inject

27. keep-alive in vue

Attributes: includeandexclude

grammar:

// 指定home组件和about组件被缓存
<keep-alive include="home,about" >
    <router-view></router-view>
</keep-alive>

// 除了home组件和about组件别的都缓存
<keep-alive exclude="home,about" >
    <router-view></router-view>
</keep-alive>

Hook function:

  • activatedTriggering when the component is activated (used) can be simply understood as triggering when entering this page
  • deactivatedTriggering when the component is not in use (inactive state) can be simply understood as triggering when leaving the page

Enter the component that enables caching

初始进入和离开 created ---> mounted ---> activated --> deactivated
后续进入和离开 activated --> deactivated

28. vue slot

Slot, also known as slot, is the content distribution mechanism of Vue. The template engine inside the component uses the slot element as the outlet for carrying and distributing content. Slot slot is a template label element of the child component, and whether and how to display this label element is determined by the parent component. There are three types of slots, default slots, named slots and scoped slots.

Default slot: also known as anonymous slot, when the slot does not specify a name attribute value, a slot is displayed by default, and there is only one anonymous slot in a component.

Named slot: A slot with a specific name, that is, a slot with a name attribute. Multiple named slots can appear in a component.

Scope slot: default slot, a variant of named slot, which can be anonymous slot or named slot, the difference of this slot is that when subcomponent renders scope slot, subcomponent The data inside the component is passed to the parent component, and the parent component decides how to render the slot based on the data passed from the child component.

Implementation principle: When the child component vm is instantiated, the content of the slot tag passed in by the parent component is obtained and stored in vm.slot. The default slot is vm.slot, and the default slot is vm.slot中,默认插槽为vm.slot.default,具名插槽为vm. s l o t . x x x , x x x 为插槽名,当组件执行渲染函数时候,遇到 s l o t 标签,使用 slot.xxx,xxx 为插槽名,当组件执行渲染函数时候,遇到slot标签,使用 slot.xxxxxx为插槽名,当组件执行渲染函数时候,遇到slot标签,使用slot中的内容进行替换,此时可以为插槽传递数据,若存在数据,则可称该插槽为作用域插槽。

29.vue2和vue3区别

双向绑定更新

vue2 的双向数据绑定是利⽤ES5 的⼀个 API ,Object.defineProperty()对数据进⾏劫持 结合 发布订阅模式的⽅式来实现的。

vue3 中使⽤了 ES6 的 ProxyAPI 对数据代理,通过 reactive() 函数给每⼀个对象都包⼀层 Proxy,通过 Proxy 监听属性的变化,从⽽ 实现对数据的监控。

这⾥是相⽐于vue2版本,使⽤proxy的优势如下

1.defineProperty只能监听某个属性,不能对全对象监听 可以省去for in、闭包等内容来提升效率(直接绑定整个对象即可)

2.可以监听数组,不⽤再去单独的对数组做特异性操作,通过Proxy可以直接拦截所有对象类型数据的操作,完美⽀持对数组的监听。

获取props

vue2在script代码块可以直接获取props,vue3通过setup指令传递

API不同

Vue2使⽤的是选项类型API(Options API),Vue3使⽤的是合成型API(Composition API)

建立数据data

vue2是把数据放入data中,vue3就需要使用一个新的setup()方法,此方法在组件初始化构造得时候触发。

生命周期不同

vue2 -------- vue3

beforeCreate -> setup() 开始创建组件之前,创建的是data和method

created -> setup()

beforeMount -> onBeforeMount 组件挂载到节点上之前执行的函数。

mounted -> onMounted 组件挂载完成后执行的函数

beforeUpdate -> onBeforeUpdate 组件更新之前执行的函数。

updated -> onUpdated 组件更新完成之后执行的函数。

beforeDestroy -> onBeforeUnmount 组件挂载到节点上之前执行的函数。

destroyed -> onUnmounted 组件卸载之前执行的函数。dszhuoyi

activated -> onActivated 组件卸载完成后执行的函数

deactivated -> onDeactivated

是否支持碎片:vue2.0 只允许有一个根标签,vue3.0支持碎片化,可以拥有多个根节点

main.js文件不同:vue2中我们可以使用pototype(原型)的形式去进行操作,引入的是构造函数 vue3中需要使用结构的形式进行操作,引入的是工厂函数

diff算法不同

更好的支持ts

30.Vue3.0 所采用的 Composition Api (组合式)与 Vue2.x 使用的 Options Api(选项式) 有什么不同?

  • options Api 当组件变得复杂,导致对应属性的列表也会增长,这可能会导致组件难以阅读和理解 。composition Api它将功能定义在一起,利于查找和理解
  • Composition API tree-shaking 友好,代码也更容易压缩
  • Composition API中见不到this的使用,减少了this指向不明的情况
  • 如果是小型组件,可以继续使用Options API,也是十分友好的

31.vue3中hook

本质是一个函数,把setup函数中使用的Composition API(组合式api)进行了封装,类似于vue2中的mixin

自定义hook优势:复用代码,让setup中的逻辑更清楚易懂

32.vue组件和插件的区别

组件: Vue 组件是一个可复用的 Vue 实例,可以带有自己的状态和方法。组件可以包含其他组件,从而形成一个复杂的 UI 列表。

优点

  • 可以将代码封装成一个可复用的组件,提高开发效率。
  • 组件具有良好的可维护性,易于修改和更新。

缺点

  • 组件的功能和作用比较独立,不太适用于全局功能的扩展。
  • 组件的管理和组织需要一定的规范,否则可能会导致混乱和不易维护。

插件: Vue 插件可以扩展 Vue 的全局功能,在应用程序中可以重复使用。常见的插件如 vue-routervuexaxios 等。

优点

  • 插件可以方便地扩展 Vue 的全局功能。
  • 插件可以使代码重复利用,提高开发效率。
  • 开源社区中已经有大量的插件可以用于解决常见的问题。

缺点

  • 插件具有一定的复杂性,需要更多的学习成本。
  • 插件功能可能比较复杂,可能会导致性能下降。

33.vue修饰符

Vue中,修饰符处理了许多DOM事件的细节,让我们不再需要花大量的时间去处理这些烦恼的事情,而能有更多的精力专注于程序的逻辑处理

  • 表单修饰符
    • .lazy 懒加载,光标离开标签时,才赋值给value
    • .trim 过滤首位空格
    • .number 限制输入类型为数字或转为数字
  • 事件修饰符
    • .stop 阻止事件冒泡
    • .prevent 组织事件默认行为
    • .once 事件只触发一次
    • .capture 开启事件捕获
    • .self 事件只在自身触发
  • 鼠标按键修饰符
    • left 左键点击
    • right 右键点击
    • middle 中键点击
  • 键值修饰符
    • 普通键(enter、tab、delete、space、esc、up…)
    • 系统修饰键(ctrl、alt、meta、shift…)
  • v-bind修饰符
    • .async 对props进行双向绑定
    • .prop 设置自定义标签属性,避免暴露数据,防止污染html结构
    • .camel 将命名为驼峰命名法

34.Vue路由中,history和hash两种模式有什么区别?

hash: hash 模式是一种把前端路由的路径用井号 # 拼接在真实 URL 后面的模式。当井号 # 后面的路径发生变化时,浏览器并不会重新发起请求,而是会触发 hashchange 事件。

  • 优点:浏览器兼容性较好,连 IE8 都支持
  • 缺点:路径在井号 # 的后面,比较丑

history: history API 是 H5 提供的新特性,允许开发者直接更改前端路由,即更新浏览器 URL 地址而不重新发起请求

  • 优点:路径比较正规,没有井号 #
  • 缺点:兼容性不如 hash,且需要服务端支持,否则一刷新页面就404了

35.params和query区别

paramsquery 都是用于传递参数的,但它们的传参方式和使用场景是不同的。

params 通过路由路径传递参数,在路由配置中使用 :paramName 的形式进行声明

const router = new VueRouter({
     
     
  routes: [
    {
     
     
      path: '/user/:id',
      component: User,
    },
  ],
})

query 通过 URL 查询字符串(即问号后面的部分)传递参数,在路由地址后面使用 ? 连接多个参数键值对

不需要在router中配置 /search?q=vue 会自动匹配到search组件

区别:

  • params 适合用于必须存在的参数传递,例如用户详情页或文章详情页的访问。
  • query 适合用于可选的参数传递,例如搜索功能中关键词的传递。

36.vue2中assets和vue3中public区别 ?

在 Vue 2 中,assets 目录是默认存在的,可以直接在项目的根目录下创建,它通常用来存放组件需要的图片、样式等静态资源文件。这些文件会被打包到 JavaScript 文件中,在代码中使用相对路径引用。

在 Vue 3 中,可以通过配置 vue.config.js 文件来设置 public 目录,它的作用与 assets 目录类似,用来存放静态资源文件。但是,与 Vue 2 不同的是,public 目录下的文件不会被打包,而是会直接复制到输出目录下

37.单页应用如何提高加载速度?

  • 使用代码分割:将代码拆分成小块并按需加载(懒加载),以避免不必要的网络请求和减少加载时间。
  • 缓存资源:利用浏览器缓存来存储重复使用的文件,例如 CSS 和 JS 文件、图片等。
  • 预加载关键资源:在首次渲染之前,先提前加载关键资源,例如首页所需的 JS、CSS 或数据,以保证关键内容的快速呈现。
  • Use an appropriate image format: Choose an appropriate image format (e.g. JPEG, PNG, WebP, etc.) and compress as needed to reduce file size. For some small icons, iconfontfont files such as can be used instead.
  • Enable Gzip compression: Files are compressed using the server-side Gzip compression algorithm to reduce transfer time and bandwidth consumption.
  • Use a CDN: Use a content delivery network (CDN) to cache and deliver files to improve file download speed and reliability.
  • Optimize API requests: Minimize the number of API calls and use techniques such as caching and lazy loading to optimize the efficiency of API requests.
  • Use Server-Side Rendering: Use Server-Side Rendering (SSR) to generate HTML to reduce the time and resources required for client-side rendering. Be aware, though, that SSR can also tax your server and complicate your site.

38. Vue parent component calls the method of child component

In vue, if the parent component wants to call the method of the child component, you can add ref to the child component, and then call it through this.$refs.ref.method

<child ref="child"></child>
调用:this.$refs.child.子组件方法

39. Dom acquisition in vue3, ref is used on components

<template>
  <div class="ref">
    <h3>ref使用:</h3>
    <input type="text" ref="input" /> //  ref="input" 需要和 const input = ref(null); 相对应
  </div>
</template>

<script setup>
import {
     
      reactive, ref, createApp, onMounted } from "vue";

let state = reactive({
     
      text: "信息按钮" });
// 同名的 input来进行获取节点
const input = ref(null);
onMounted(() => {
     
     
  if (input.value) {
     
     
    input.value.focus();
  }
});
</script>
<style scoped></style>

40. Progressive framework understanding

Progressive: It can be understood as not doing more than the duty

Personal understanding: The one with the fewest claims, initially built on the basis of the basic framework, will continue to expand with demand

41. Page initialization flashes

Cause: When the network speed is slow and vue.jsthe file has not been loaded, the words {{message}} will be displayed on the page. Knowing that vue creates an instance and compiles the template, the dom will be replaced, so the screen is flashing during this process moveable.

So to solve this problem, you need to set [v-cloak] {display: none} in the style style. In general, v-clock is a best practice to solve the page flicker caused by slow initialization, which is very practical for simple projects.

But in engineering projects, such as projects using webpack and vue-router, the html structure is just an empty div element, and the rest of the content is completed by routing to mount different components, so v is not needed -cloak.

42. What is the problem with the same vue attribute name and method name?

In vue2, this 属性overrides 盖掉 methodsthe method in . In other words, this method will not be called correctly.

In vue3, an error is reported

43. How to dynamically bind class and style

The dynamic binding of class and style is generally realized through objects or arrays

Object writing method: It is suitable for the name of the style to be bound. The style is determined, but it is dynamically determined whether to use it or not.

Array writing: Applicable to the style name to be bound and the style is uncertain.

<div v-bind:class="{ active: isActive }"></div> //对象写法
<div v-bind:class="[activeClass, errorClass]"></div> //数组写法

44. The pit encountered by vue

  • data must be a function, not an object
  • The functions managed by vue should not be written as arrow functions
  • Add property page does not refresh
  • The sub-routing path does not need to add **/**, path='new'

45. v-if and v-for priority

In practice, neither vue2 nor vue3 should use v-if and v-for together.

In vue 2.x, when using v-if and v-for on an element at the same time, v-for will take precedence.

In vue 3.x, v-if always takes precedence over v-for.

The priority of v-for in vue2 is higher than that of v-if. When put together, the loop will be executed first to judge the condition, and if a small number of elements in the value rendering list have to be traversed every time it is re-rendered list, which is a waste of resources.

The priority of v-if in vue3 is higher than that of v-for, so when v-if is executed, it will call the corresponding variable if it does not exist, it will cause an exception

46. ​​The core principle of vue

Data-driven, building systems

47. Vue comes with animation components, transition

Components are provided by Vue to wrap element components that require animation effects. Components can be used to easily animate the entry and exit of elements.

<template>
  <div>
    <button @click="visible = !visible">Toggle</button>
    <transition name="fade">
      <p v-if="visible">Hello, World!</p>
    </transition>
  </div>
</template>

<script>
export default {
     
     
  data() {
     
     
    return {
     
     
      visible: false
    }
  },
}
</script>

<style>
.fade-enter-active, .fade-leave-active {
     
     
  transition: opacity .5s;
}
.fade-enter, .fade-leave-to {
     
     
  opacity: 0;
}
</style>

48. Working principle of vue-loader

  1. Cut a .vue file into three parts: template , script and styles .
  2. template 部分 通过 compile 生成 renderstaticRenderFns
  3. 获取 script 部分 返回的配置项对象 scriptExports
  4. styles 部分,会通过 css-loadervue-style-loader, 添加到 head 中, 或者通过 css-loaderMiniCssExtractPlugin 提取到一个 公共的css文件 中。
  5. 使用 vue-loader 提供的 normalizeComponent 方法, 合并 scriptExports、render、staticRenderFns, 返回 构建vue组件需要的配置项对象 - options, 即 {data, props, methods, render, staticRenderFns…}

49.vue的diff算法

diff整体策略为:深度优先,同层比较

  • When the data changes, the subscriber watcherwill call patchthe real DOMpatch

  • By isSameVnodemaking a judgment, if it is the same, call patchVnodethe method

  • patchVnode

    did the following:

    • Find the corresponding truth dom, calledel
    • If both have text nodes and are not equal, set elthe text node to Vnodethe text node
    • If oldVnodethere is a child node and VNodethere is no child node, delete elthe child node
    • If there is oldVnodeno child node VNode, then VNodethe child node will be realized and added toel
    • If both have child nodes, execute updateChildrenfunction compare child nodes
  • updateChildren

    Mainly did the following operations:

    • Set the old and new VNodehead and tail pointers
    • Compare the old and new head and tail pointers, move closer to the middle in a loop, call to repeat the process according to the situation patchVnode, patchcall to createElemcreate a new node, find a keyconsistent VNodenode from the hash table, and then divide the situation into operations

50. The difference between vue and jquery

设计理念

Vue.js is a modern JavaScript framework focused on building large, maintainable web applications. The core of Vue.js is componentization, which provides a way to decompose a page into independent, reusable components, and manage the dependencies between these components very easily. At the same time, Vue.js also has built-in functions such as state management, routing, and construction tools, making it easier to build complex web applications.

而 jQuery 则是一个早期的 JavaScript 库,主要关注的是 DOM 操作和处理事件。它的设计理念是将 JavaScript 代码尽可能地简单化,使得使用者可以很容易地完成一些常见的操作(如选择元素、修改样式、处理事件等)。在 jQuery 中,通过链式调用和函数式变成的设计,可以使得代码变得非常简洁易读。

用途

Vue.js 主要用于构建大型的、复杂的 Web 应用程序,它提供了诸如组件化、状态管理、路由等功能,非常适合构建单页面应用(SPA)。

而 jQuery 则更多地用于简化 DOM 操作和事件处理,它适用于编写小型的 Web 应用程序或较为简单的交互效果。同时,由于 jQuery 在浏览器兼容性、性能等方面的优势,它也被广泛应用于一些成熟的网站和CMS系统中。

51.说说你对 SPA 单页面的理解,它的优缺点分别是什么?

SPA( single-page application )仅在 Web 页面初始化时加载相应的 HTML、JavaScript 和 CSS。一旦页面加载完成,SPA 不会因为用户的操作而进行页面的重新加载或跳转;取而代之的是利用路由机制实现HTML 内容的变换,UI 与用户的交互,避免页面的重新加载。

  • 优点:
    用户体验好、快,内容的改变不需要重新加载整个页面,避免了不必要的跳转和重复渲染;
    基于上面一点,SPA 相对对服务器压力小;
    前后端职责分离,架构清晰,前端进行交互逻辑,后端负责数据处理;
  • Disadvantages:
    Time-consuming initial loading: In order to realize the functions and display effects of single-page web applications, JavaScript and CSS need to be loaded when the page is loaded, and some pages are loaded on demand; forward and backward routing management: because
    single-page applications are placed on one page All the content is displayed in the browser, so you can’t use the forward and backward functions of the browser. All page switching needs to establish a stack management by yourself;
    SEO is more difficult: since all content is dynamically replaced and displayed on one page, it has a certain advantage in SEO Natural weakness.

52. How to understand the one-way data flow of Vue?

All props form a single downward binding between their parent and child props: updates to the parent prop flow down to the child components, but not the other way around.
This prevents accidental changes to the parent component's state from child components, which can make your app's data flow difficult to understand.
In addition, every time the parent component is updated, all props in the child component will be refreshed with the latest values.
This means you should not change props inside a child component. If you do this, Vue will issue a warning in the browser's console.
When a child component wants to modify it, it can only send a custom event through $emit, and the parent component will modify it after receiving it.

53. Can the parent component monitor the life cycle of the child component?

For example, if there is a parent component Parent and a child component Child, if the parent component monitors that the child component is mounted, it will do some logic processing, which can be achieved by the following writing method:

// Parent.vue
<Child @mounted="doSomething"/>

// Child.vue
mounted() {
  this.$emit("mounted");
}

The above needs to manually trigger the event of the parent component through $emit. The simpler way is to listen to it through @hook when the parent component references the child component, as shown below:

//  Parent.vue
<Child @hook:mounted="doSomething" ></Child>

doSomething() {
   console.log('父组件监听到 mounted 钩子函数 ...');
},

//  Child.vue
mounted(){
   console.log('子组件触发 mounted 钩子函数 ...');
},    

// 以上输出顺序为:
// 子组件触发 mounted 钩子函数 ...
// 父组件监听到 mounted 钩子函数 ...

Of course, the @hook method can not only monitor mounted, but also other life cycle events, such as created, updated, etc. can be monitored.

54. What are the main aspects of Vue3.0 performance improvement?

  • diff algorithm optimization
  • Static promotion: Vue3For elements that do not participate in the update, static promotion will be performed, which will only be created once and reused directly during rendering
  • Remove some uncommon APIs, and most importantlyTree shanking
  • responsive system

55. What is MVVM? What is the difference compared to MVC? What is MVP again?

MVC organizes the code structure by separating Model, View and Controller. When the user interacts with the page, the event trigger in the Controller starts to work. By calling the Model layer, the modification of the Model is completed, and then the Model layer notifies the View layer to update.

The VM in the MVVM pattern refers to ViewModel, which automates the synchronous update of View and Model through two-way data binding. When the Model changes, the ViewModel will be updated automatically; if the ViewModel changes, the View will also be updated.

In the MVP mode, the interface of the View layer is exposed to the Presenter, so we can bind the changes of the Model and the changes of the View in the Presenter, so as to realize the synchronous update of the View and the Model

56. The difference between hook in vue and hook in react

In React, hook is a function that allows you to add state, effect and other functions to function components. The hooks in React include useState, useEffect, useContext, etc. Using hooks can avoid cumbersome life cycle methods, this and other problems that may occur when using class components.

In Vue, hooks are called lifecycle hook functions, which are callback functions that are automatically called during component instantiation. The lifecycle hook functions in Vue include beforeCreate, created, beforeMount, mounted, etc. They can be used to control the life cycle of components, and to perform specific operations at specific stages of the component life cycle.

57. The difference between Redux and Vuex

redux is a common js library, and vuex is dedicated to serving vue

Same point:

  1. state shared data
  2. Consistent process: define global state, trigger, modify state
  3. The principle is similar, and the store is injected globally.

difference:

  1. Vuex defines five objects of state, getter, mutation, action, and module; redux defines state, reducer, and action;
  2. There are two ways to trigger Vuex: commit synchronous and dispatch asynchronous; both redux synchronous and asynchronous use dispatch;
  3. Actions in Vuex have more complex asynchronous ajax requests; actions in redux can be simple or complex, simply send data objects directly ({type:xxx, your-data}), and complex calls for asynchronous ajax (depending on the redux-thunk plugin) .
  4. Redux uses immutable data, while Vuex's data is mutable. Redux replaces the old state with the new state every time, while Vuex modifies it directly;
  5. When Redux detects data changes, it uses diff to compare differences, while Vuex actually uses the same principle as Vue, and uses getter/setter to compare.

58. What problems does vue server-side rendering (SSR) solve?

Vue server-side rendering (SSR) achieves faster page loading, better search engine optimization, and better user experience by pre-generating the HTML string of the Vue component on the server and sending it to the client. Server-side rendering solves many problems in SPA (Single Page Application) applications, such as:

  1. SEO (Search Engine Optimization) Issues: Since traditional SPA applications are built in the browser, search engines cannot properly index their content. With Vue SSR, it is possible to render HTML strings on the server and provide better friendly pages to search engines.
  2. Performance issues: SPA applications require a lot of JavaScript code to initialize and interact with the application. This can lead to slow page load times and a poor user experience. Using Vue SSR, the full logo of the initial HTML can be rendered faster in the browser, with the necessary JavaScript embedded in it. This results in faster page loads and a better user experience.
  3. 首屏渲染问题:传统的SPA应用程序在首次加载时可能会需要大量时间才能呈现第一个屏幕,直到JavaScript代码完成下载并执行。使用Vue SSR,可以在服务器上呈现组件,并将其作为HTML字符串发送到客户端,从而实现快速呈现首屏的目标。

59.Vue 3.0中Treeshaking特性是什么,并举例进行说明?

Tree shaking 是一种通过清除多余代码方式来优化项目打包体积的技术

Tree shaking是基于ES6模板语法(importexport),主要是借助ES6模块的静态编译思想,在编译时就能确定模块的依赖关系,以及输入和输出的变量

Tree shaking无非就是做了两件事:

  • 编译阶段利用ES6 Module判断哪些模块已经加载
  • 判断那些模块和变量未被使用或者引用,进而删除对应代码

作用:

  • 减少程序体积(更小)
  • 减少程序执行时间(更快)
  • 便于将来对程序架构进行优化(更友好)

60. 虚拟 DOM 的优缺点?

优点:

  • 保证性能下限: 框架的虚拟 DOM 需要适配任何上层 API 可能产生的操作,它的一些 DOM 操作的实现必须是普适的,所以它的性能并不是最优的;但是比起粗暴的 DOM 操作性能要好很多,因此框架的虚拟 DOM 至少可以保证在你不需要手动优化的情况下,依然可以提供还不错的性能,即保证性能的下限;
  • 无需手动操作 DOM: 我们不再需要手动去操作 DOM,只需要写好 View-Model 的代码逻辑,框架会根据虚拟 DOM 和 数据双向绑定,帮我们以可预期的方式更新视图,极大提高我们的开发效率;
  • 跨平台: 虚拟 DOM 本质上是 JavaScript 对象,而 DOM 与平台强相关,相比之下虚拟 DOM 可以进行更方便地跨平台操作,例如服务器渲染、weex 开发等等。

缺点:

  • 无法进行极致优化: 虽然虚拟 DOM + 合理的优化,足以应对绝大部分应用的性能需求,但在一些性能要求极高的应用中虚拟 DOM 无法进行针对性的极致优化。

61. 虚拟 DOM 实现原理?

The realization principle of virtual DOM mainly includes the following three parts:

  • Use JavaScript objects to simulate the real DOM tree and abstract the real DOM;
  • diff algorithm — compare the differences between two virtual DOM trees;
  • The pach algorithm — applies the difference of two virtual DOM objects to the real DOM tree.

62. What is the function of key in Vue?

key is the unique mark of vnode in Vue, through this key, our diff operation can be more accurate and faster.
The diff process of Vue can be summarized as: oldCh and newCh each have two head and tail variables oldStartIndex, oldEndIndex and newStartIndex, newEndIndex, they will compare the new node and the old node in pairs, that is, there are 4 comparison methods in total: newStartIndex and oldStartIndex , newEndIndex and oldEndIndex, newStartIndex and oldEndIndex, newEndIndex and oldStartIndex, if none of the above 4 comparisons match, if the key is set, the key will be used for comparison again. During the comparison process, the traversal will lean towards the middle, once StartIdx > EndIdx indicates that at least one of oldCh and newCh has been traversed, and the comparison will end.
So the function of key in Vue is: key is the unique mark of vnode in Vue, through this key, our diff operation can be more accurate and faster!

  • More accurate: because it is not in-place multiplexing with key, in-place multiplexing can be avoided in the sameNode function a.key === b.key comparison. So it will be more accurate.
  • Faster: Use the uniqueness of the key to generate a map object to obtain the corresponding node, which is faster than the traversal method. The source code is as follows:
function createKeyToOldIdx (children, beginIdx, endIdx) {
  let i, key
  const map = {}
  for (i = beginIdx; i <= endIdx; ++i) {
    key = children[i].key
    if (isDef(key)) map[key] = i
  }
  return map
}

62. How to use Object.defineProperty, three parameters? , what is the effect?

Object.defineProperty() 方法会直接在一个对象上定义一个新属性,或者修改一个对象的现有属性,并返回此对象。

     obj:需要定义属性的对象
     prop:需要定义的属性
     {}:要定义或修改的属性描述符。
	     value: "18",         // 设置默认值 (与 get() 互斥)
	     enumerable: true,    //这一句控制属性可以枚举 enumerable 改为true 就可以参与遍历了   默认值false
	     writable: true,      // 该属性是否可写   默认值false (与 set() 互斥)
	     configurable: true,  // 该属性是否可被删除   默认值false
	      get // 当有人读取 prop 的时候  get函数就会调用,并且返回就是 sss 的值
	      set // 当有人修改 prop 的时候  set函数就会调用, 有个参数这个参数就是修改后的值

63.reactive与ref的区别?

从定义数据角度对比:

  • ref用来定义:基本类型数据

  • reactive用来定义对象(或数组)类型数据

    备注:ref也可以用来定义对象(或数组)类型数据, 它内部会自动通过reactive转为代理对象。

从原理角度对比:

  • ref通过Object.defineProperty()的get与set来实现响应式(数据劫持)。
  • reactive通过使用Proxy来实现响应式(数据劫持), 并通过Reflect操作源对象内部的数据。

从使用角度对比:

  • ref定义的数据:操作数据需要.value,读取数据时模板中直接读取不需要.value。
  • reactive定义的数据:操作数据与读取数据:均不需要.value。

64.v-on可以监听多个方法吗?

可以一个元素绑定多个事件的两种写法

<a v-on='{click:DoSomething,mouseleave:MouseLeave}'>doSomething</a>
<button @click="a(),b()">点我ab</button>

65.vue3中如何获取refs,dom对象的方式?vue2中如何使用?

vue3:

(1) setup函数方法内,获取单个ref属性绑定的dom元素:先定义一个空的响应式数据ref定义的,你想获取哪个dom元素,在该元素上使用ref属性绑定该数据即可,通过ref.value即可获取到dom节点

(2) 获取多个ref属性绑定的dom元素。使用ref绑定一个函数,在函数里把dom添加到数组里面

//vue2
<h3 ref="myref">myref</h3>

//获取
this.$refs.myref

66.shallowReactive和shallowRef的区别

(1) shallowReactive:只处理对象最外层的响应式(浅响应式)

(2) shallowRef:只处理基本数据类型的响应式,不进行对象的响应式处理。

(3) 应用场景:

​ ① 如果有一个对象数据,结构比较深,但变化时候,只是外层属性变化,使用shallowReactive。

​ ② 如果有一个对象数据,后续功能不会修改改对象中的属性,而是生成新的对象来替换,使用shallowRef。

67.provide与inject如何使用

(1) 父子组件传参可以通过props和emit来实现,但是当组件的层次结构比较深时,props和emit就没什么作用了。vue为了解决这个提出了Provide / Inject;provider/inject:简单的来说就是在父组件中通过provider来提供变量,然后在子组件中通过inject来注入变量

(2) provide需要先引入,我们将需要传递给下级组件的变量通过provider(‘传输key’,变量)

(3) Inject,下级组件通过变量方式接收,person= inject(‘传输key’)

68.toRaw 与 markRaw是什么作用?

(1) toRaw :将一个由reactive生成的响应式对象转化为普通对象

使用场景:用于读取响应式对象对应的普通对象,对这个普通对象的所有操作,不会引起页面更新.

(2) markRaw:标记一个对象,使其永远不会再成为响应式对象。

应用场景:有些值不应被设置为响应式的,例如复杂的第三方类的库,当渲染具有不可变数据源的大列表时,跳过响应式转换可以提高性能

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0gRb8BE4-1686967105050)(C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\1685349361040.png)]

69.Readonly和shallowReadonly理解

readonly:让一个响应式数据变为只读的(深只读),readonly是一个函数,他会接收一个响应式的数据

shallowReadonly:让一个响应式数据变为只读的(浅只读),shallowReadonly只限制对象中的第一层数据(不能改动,如:salary),但是嵌套的深层次的value属性值 是可以更改的,我们点击更改按钮测试就能发现,被shallowReadonly包裹的对象的深层次值改变了。

70.toref和torefs区别

toReftoRefs 可以用来复制 reactive 里面的属性然后转成 ref,而且它既保留了响应式,也保留了引用

toref(变量,属性),torefs(整个变量)

区别:

  • 在插值表达式中{ {}}:
    • 访问 toRefs 的值,需要带上 .value 如果不带上,就会出现双引号 { {user.name.value}}
    • 访问 toRef 的值,不需要带上 .value { {user.name}}
  • 转换属性:
    • toRef: 复制 reactive 里的单个属性并转成 ref
    • toRefs: 复制 reactive 里的所有属性并转成 ref

71.学习 EventBus

首先,在你的项目中创建一个 eventBus.js 文件,并定义一个空的 EventBus 对象:

import Vue from 'vue';
export const EventBus = new Vue();

发送事件

import {
    
     EventBus } from './eventBus.js';

// 发送名为 'myEvent' 的事件
EventBus.$emit('myEvent', data);

接收事件

import {
    
     EventBus } from './eventBus.js';

EventBus.$on('myEvent', (data)=>{
    
    });

取消监听

EventBus.$off('myEvent');

72.vue2过滤器(vue3取消)

filter 过滤器是一种很常用的功能,它可以用于对数据进行格式化、排序、筛选等操作。在使用过程中,我们只需要在模板表达式中使用管道符 |,并将要使用的过滤器的名称作为参数传递进去即可。

全局过滤器:Vue.filter(‘过滤器名称’,function(){})

局部过滤器:filter选项

filters: {
    
    
    //filterName过滤器名,value是'|'之前的数据
    filterName(value) {
    
    
      if (!value) return '';
      return '你好'+value.toString()
    }
  }

73. vue可以通过计算属性监听计算属性吗

答案:不可以

Computed properties depend on other property values, so we can listen to changes in these property values ​​in the calculated property and perform some related operations. However, a computed property cannot directly monitor the change of another computed property, because one 计算属性的值不是响应式的, when the value of the property it depends on changes, only itself will recalculate, without triggering the update of other computed properties


6. TypeScript

1. TypeScript basic data types

Primitive data type:

  • boolean Boolean value
  • number value
  • string string
  • null empty value
  • undefined undefined
  • Symbol (new type in ES6)

Non-primitive data types:

  • Array arr: number[] arr: Array

  • Tuple ancestor x: [string, number]

  • enum enumeration

enum Color {
     
     Red, Green, Blue};
let c: Color = Color.Blue;//默认情况下,从 0 开始为元素编号。
console.log(c);    // 输出 2

enum Person {
     
     
 name = "NAME",
 age = "AGE",
 love = "LOVE",
 hobby = "HOBBY",
}
console.log(Person.name); // NAME
console.log(Person.hobby); // HOBBY
  • never the type of value that never exists

  • void

//void 类型像是与 any 类型相反,它表示没有任何类型。 当一个函数没有返回值时,你通常会见到其返回值类型是 void。
function hello(): void {
     
     
   alert("Hello ts");
}
  • any any type

  • union type

//联合类型(Union Types)表示取值可以为多种类型中的一种。
let num: string | number;
num = "seven";
num = 7;
  • function type
  • unknown indicates an unknown type, and unknownthe variables and parameters using annotations must undergo type checking and conversion before they can be used.

2.void和undefined

let unde: void = undefined;
let nu: void = null;

let un: undefined = undefined;
let nu: null = null;

//与 void 的区别是,undefined是所有类型的子类型。也就是说 undefined 类型的变量,可以赋值给 number 类型的变量

let num: number = undefined;

let un: undefined;
let num2: number = un;

3. TypeScript class modifiers

TypeScript supports accessors public, private and protected, which determine the accessibility of class members.

public (public): All properties and methods defined as public can be accessed anywhere.

Private (private): All properties and methods defined as private can only be accessed within the class definition.

protected (protected): All members of the class and its subclasses can access them. But instances of this class are not accessible

4. How to define an array whose elements may be of string type or numerical type

//通过不同方式使用联合类型写法  |

// 方法1:
let arr1: (number | string)[] = [1]
arr1.push(1)
arr1.push('3')

// 方法2:
let  arr2 : Array<string | number> = [1, '2']
arr2.push(1)
arr2.push('3')

// 方法3:
type newType = number|string
let arr3:newType []= [3]
arr3.push(1)
arr4.push('5')

5. TypeScript interface

An interface is a declaration of a series of abstract methods. 方法特征的集合These methods should be abstract and need to be implemented by specific classes, and then third parties can use this set of abstract method calls to make specific classes execute specific methods.

//接口定义 interface
interface interface_name {
    
     
}
//以下实例中,我们定义了一个接口 IPerson,接着定义了一个变量 customer,它的类型是 IPerson。
//customer 实现了接口 IPerson 的属性和方法。
interface IPerson {
    
     
    firstName:string, 
    lastName:string, 
    sayHi: ()=>string 
} 
 
var customer:IPerson = {
    
     
    firstName:"Tom",
    lastName:"Hanks", 
    sayHi: ():string =>{
    
    return "Hi there"} 
} 
 
console.log("Customer 对象 ") //Customer 对象
console.log(customer.firstName) //Tom
console.log(customer.lastName)//Hanks
console.log(customer.sayHi()) //Hi there

6. The difference between TypeScript object and TypeScript interface

对象:对象是TS中一种数据类型,可以用来存储多个数据属性和方法,并且可以通过对象字面量或者构造函数来创建实例

接口:接口是TS中定义数据结构的规范,主要用于描述对象的形状,即对象应该包含哪些属性和方法,但不提供实现。接口可以作为一个契约,确保其他代码符合其规范

//对象
let person = {
    
    
  name: "Tom",
  age: 18,
  sayHi: function() {
    
    
    console.log("Hi");
  }
};

console.log(person.name); // Tom
person.sayHi(); // Hi

//接口
interface Person {
    
    
  name: string;
  age: number;
  sayHi(): void;
}

let person: Person = {
    
    
  name: "Tom",
  age: 18,
  sayHi() {
    
    
    console.log("Hi");
  }
};

console.log(person.name); // Tom
person.sayHi(); // Hi

类型别名及类型符号csdn详情参考

7.TypeScript类型别名

上述介绍了ts中的数据类型和接口,但是在开发过程中 不可避免的会遇到各种复杂类型 , 有些数据类型更灵活、复杂,那么此时,类型别名是一种非常有用的工具,它可以帮助我们简化代码,提高代码的可读性和可维护性

基本用法: type 类型名 = 类型值

type Name = string;
type Age = number;
type Person = {
    
    
  name: Name;
  age: Age;
  sayHi(): void;
};

let person: Person = {
    
    
  name: "Tom",
  age: 18,
  sayHi() {
    
    
    console.log("Hi");
  }
};

console.log(person.name); // Tom
person.sayHi(); // Hi

8.TypeScript字面量类型

字面量类型(Literal Types)用来表示具体的字面量值,包括字符串、数字、布尔值等。它们可以作为类型注解的一部分,用来限制变量、函数参数、函数返回值等的取值范围

  • 数字字面量,字符串字面量,布尔字面量,空值字面量,枚举字面量

    //数字字面量
    type Num = 10
    const num: Num = 10
    const num2: Num = 20 // 抛错,不能将20赋值给类型10
    
    //字符串字面量
    type Str = "a"
    const num: Str = "a"
    
    //布尔字面量
    type Bool = false
    const bool: Bool = false
    
    //空值字面量
    type Void = void;
    const isNull: Void = null
    const isUndefined: Void = undefined
    const isVoid: Void = void 0
    
    //枚举字面量
    enum Color {
          
          
        Red = 1,
        Green,
        Blue
    }
    type colorBlue = Color.Blue
    const blue: colorBlue = 3
    

9.TypeScript类型符号

TypeScript中的类型符号是用来声明变量类型的符号,主要有以下几种:

  1. ::用于声明变量的类型,例如:let a: number = 10; 表示声明一个名为a的变量,并将其类型标注为number。
  2. ?:用于表示某个属性或参数是可选的,例如:interface Person { name: string; age?: number; } 表示Person接口的age属性是可选的。
  3. []:用于表示数组类型,例如:let arr: number[] = [1, 2, 3]; 表示声明一个名为arr的数组,其中元素类型为number。
  4. ():用于表示函数类型,例如:function add(a: number, b: number): number { return a + b; } 表示声明一个名为add的函数,其中参数a和b的类型均为number,返回值类型也为number。
  5. |: used to represent the union type, for example: let c: number | boolean = 10;to declare a variable named c whose type is number or boolean.
  6. &: used to represent the intersection type, for example: interface A { a: number; } interface B { b: string; } type C = A & B;means to define a cross type named C, which contains both the properties and methods of the two interfaces A and B

10. TypeScript cross type

Intersection Types can be used to combine multiple types into one. The intersection type is used 且符号&to connect two or more types; it is worth noting that the intersection type is generally used to define complex data types such as objects. If the intersection type is used to define the basic type, it will be converted to the never type , because a type is impossible Both basic types

& 连接的是简单联合类型,则产生的新类型是 & 符号两边类型的公有类型。

//交叉基础类型,错误示范
type str = string
type num = number
type StrAndNum = str & num // never类型

//正确示范
type information = {
    
    
    name: string
    age?: number  //?是可选类型,可以下放交叉不使用
}
type information2 = {
    
    
    readonly address: string
}
 
type user = information & information2
 
const whiteDog: WhiteDog = {
    
    
    name: "lc",
    address: "中国",
}

//` & 连接的是简单联合类型
type A = string | number
type B = string[] | number
// C是A和B共有的类型,number类型
type C = A & B

11. Generic objects

Generics: Use angle brackets <> to declare type parameters (there can be more than one) to represent a temporarily unknown type, and pass in the corresponding type (or automatically deduced by TS) to replace the corresponding occurrence of the type parameter when declaring the variable places, thereby replacing abstract, unknown types with concrete, known types. A type parameter refers to a type, such as <T, K, U, ...> each refer to a temporarily unknown type. When generics are used to define object types, generic objects are obtained.

// 类型T代表一种暂时未知的类型
interface PersonInfo<T> {
    
    
  info: T
}
// 传入类型变量string,这时候string就会在相应的地方替换原来的T
let p1: PersonInfo<string> = {
    
    
  info: 'cc'
}

let p2: PersonInfo<number> = {
    
    
  info: 18
}

let p3: PersonInfo<'男' | '女'> = {
    
    
  info: "男"
}

Generics can also be used in type aliases . In addition to defining object types, type aliases can also use generics to define various other types. Therefore, we can use generic nesting to define more complex type structures

12. Type assertions

Type assertion (Type Assertion) is a way to explicitly tell the compiler the type of a variable, which allows us to manually specify the type of a variable, thereby bypassing the TypeScript compiler's check of the variable type

//断言两种方式,<>和as

let str: unknown
const len: number = (<string>str).length

let str: unknown
const len: number = (str as string).length

Personal understanding: A variable is defined in advance and the type is set for it, but in other scenarios, this variable needs to be of another type in order to avoid error reporting by 断言specifying it as the required type

13. unknown type

类型unknown表示一个未知的类型。与any类型不同,使用unknown标注的变量和参数必须经过类型检查和转换后才能使用。

应用场景:

  • 当我们不知道某个变量的类型时,在某些情况下可以先把它标注为unknown类型,并在使用前进行类型检查或类型转换。
  • 当我们编写一些通用的函数或库时,为了避免与不同的代码库之间发生类型冲突,可以使用unknown类型来定义变量和参数。
function processValue(value: unknown) {
    
    
  if (typeof value === "string") {
    
    
    console.log(value.toUpperCase());
  } else if (typeof value === "number") {
    
    
    console.log(value.toFixed(2));
  }
}

let val1: unknown = "hello";
processValue(val1); // 输出HELLO

let val2: unknown = 3.1415;
processValue(val2); // 输出3.14

let val3: unknown = true;
processValue(val3); // 编译时错误:boolean类型不能转换为string或number类型

从上面的例子中可以看出,如果不进行类型检查或类型转换,使用unknown类型的变量会导致编译时错误。但是,通过类型检查和转换,我们可以安全地使用这个变量并避免类型错误。

14.函数重载

函数名称相同,但是参数的个数或者类型不同。

// 函数的定义
function add(num1: number, num2: number): number;
function add(num1: string, num2: string): string;

// 函数的实现
function add(num1: any, num2: any): any {
    
    
    return num1 + num2;
}

15.抽象类

通过abstract定义抽象类

在 TypeScript 中,抽象类是一种特殊的类,它本身不能被实例化,而只能被继承。抽象类可以包含抽象方法(即只有方法签名,没有实现),用于定义一些基本的行为或约束子类必须实现的方法,以及普通的具体方法,用于提供一些默认的实现。

// 不可以 new Animal 只能继承抽象类
abstract class Animal {
    
    
  abstract makeSound(): void;
  move(distanceInMeters: number = 0) {
    
    
    console.log(`Animal moved ${
      
      distanceInMeters}m.`);
  }
}

class Dog extends Animal {
    
    
  makeSound() {
    
    
    console.log("Woof! Woof!");
  }
}

let dog = new Dog();
dog.makeSound(); //  "Woof! Woof!"
dog.move(10); // "Animal moved 10m."

16.类型守卫,typeof 以及 instanceof

typeof 类型守卫:使用 typeof 运算符可以判断一个变量的类型是 string、number、boolean、symbol 或 undefined。

instanceof 类型守卫:使用 instanceof 运算符可以判断一个变量是否为指定类的实例。它的使用方法是在检测对象的同时指定一个构造函数作为比较对象

//typeof
function example(value: string | number) {
    
    
  if (typeof value === "string") {
    
    
    console.log(`The value is a string: ${
      
      value}`);
  } else {
    
    
    console.log(`The value is a number: ${
      
      value}`);
  }
}
example("hello"); // Output: "The value is a string: hello"
example(42); // Output: "The value is a number: 42"

//instanceof
class MyClass {
    
    }
function example(input: MyClass | string) {
    
    
  if (input instanceof MyClass) {
    
    
    console.log("The input is an instance of MyClass.");
  } else {
    
    
    console.log(`The input is a string: ${
      
      input}`);
  }
}
example(new MyClass()); // Output: "The input is an instance of MyClass."
example("hello"); // Output: "The input is a string: hello"

17.TypeScript 编译上下文

在 TypeScript 中,编译上下文是指编译器对源代码进行类型检查和转换时所使用的环境和规则

编译上下文可以包含以下几个方面:

  1. Compilation options: The compiler can configure various compilation options through command line parameters or tsconfig.json files, including output directory, module parsing method, generated JavaScript version, etc.
  2. Type checking: The compiler performs type checking on the source code to catch possible type errors and provide more accurate type inference. The type checking process involves concepts such as type system, type annotation, and type inference.
  3. Type conversion: During compilation, TypeScript converts language features used in source code (such as classes, interfaces, generics, enums, namespaces, etc.) into corresponding JavaScript code. During this process, the compiler will also perform some optimizations and adjustments.
  4. Declaration file processing: TypeScript supports the use of declaration files to describe the type information of JavaScript libraries and modules to improve compatibility with third-party libraries and development efficiency. The compiler will automatically search for declaration files in the project, or for libraries without declaration files, it can also be automatically generated by third-party tools.
  5. Module resolution: During the compilation process, the compiler needs to resolve the dependencies between modules in order to correctly generate the corresponding JavaScript code files. Module resolution involves issues such as module paths, module aliases, and custom resolution.

18.tsconfig.json

tsconfig.json is a configuration file used to configure the TypeScript compiler. Through this configuration file, you can specify the rules and options used by the compiler to implement a custom compilation process and adjust the output

{
    
    
  "compilerOptions": {
    
    
    /* 基本选项 */
    "target": "es5",                       /* 指定 ECMAScript 目标版本: 'ES3' (default), 'ES5', 'ES6'/'ES2015', 'ES2016', 'ES2017', or 'ESNEXT' */
    "module": "commonjs",                  /* 指定模块化代码生成方式: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext' */
    "lib": ["es6", "dom"],                 /* 指定要包含在编译中的库文件,默认为所有支持的库 */
    "outDir": "./dist",                    /* 指定输出目录 */
    "rootDir": "./src",                    /* 指定源代码目录 */
  
    /* 详细选项 */
    "strict": true,                        /* 启用所有严格类型检查选项 */
    "noImplicitAny": true,                 /* 在表达式和声明上有隐含的 any 类型时报错 */
    "strictNullChecks": true,              /* 启用严格的 null 检查 */
    "noImplicitThis": true,                /* 当 this 表达式值为 any 类型的时候,生成一个错误 */
    "alwaysStrict": true,                  /* 以严格模式检查每个模块,并在模块内部启用 "use strict" */
  
    /* 配置文件扩展选项 */
    "resolveJsonModule": true,             /* 允许导入 .json 模块 */
    "esModuleInterop": true,               /* 自动生成命名空间导入 (import * as module from "module") */
    "skipLibCheck": true                    /* 跳过对声明文件的检查 */
  }
}

19. Difference between TypeScript and JavaScript

js does not have the concept of overloading, but ts can overload

ts adds interface interface, generic type, class, class polymorphism, inheritance, etc.

Compared with the basic type of js, ts adds void/never/any/tuple/enumeration/and some advanced types

选择学习

  1. Type system: TS is a programming language with static type checking, which supports explicitly specifying the data type of variables in the code, declaring the input and output types of functions, defining interfaces and classes, etc. JS is a dynamically typed language, and variable types are determined dynamically at runtime.
  2. Compilation method: TS is a compiled language, which requires a compiler to convert TS code into equivalent JS code before it can be executed in a browser or Node.js. And JS is an interpreted language, which is interpreted and executed directly by the runtime.
  3. 扩展语法:TS 支持 ECMAScript 标准中定义的所有语法,并且还提供了一些自己的扩展语法,例如枚举类型、泛型、元组类型等。JS 则不支持所有扩展语法,并且在新标准发布前需要等待浏览器厂商的实现或者使用 polyfill 进行补丁。
  4. 开发工具:TS 具备良好的 IDE 集成、语法高亮、代码提示、错误检查等功能,开发体验更加友好。JS 的开发工具则相对简单,主要是一些文本编辑器和浏览器控制台。
  5. 生态环境:TS 是由微软开发并维护的项目,有着全球范围内的活跃社区和丰富的第三方库。JS 则更加开放和自由,生态环境更加广泛和多样化。

七、React篇

1.react理解

  • React,用于构建用户界面的 JavaScript 库,只提供了 UI 层面的解决方案 ,是渐进式框架,采用mvc架构
  • 特性: JSX 语法 , 单向数据绑定 , 虚拟 DOM , 声明式编程 ,组件化开发

2.react-router 里的 标签和 标签有什么区别?

  • react-router 接管了其默认的链接跳转行为,与传统的页面跳转有区别的是,Link 的 “跳转” 行为只会触发相匹配的对应的页面内容更新,而不会刷新整个页面。
  • link做了哪些事:1.有onclick就执行onclick,2.click的时候阻止a标签默认事件,3.根据跳转href用history跳转,此时只是链接变了,并没有刷新页面

3.React Jsx转换成真实DOM过程?

  • 首先我们知道Jsx代码是不会被浏览器识别的,最终都会转化为 React.createElement 形式,babel实现这个过程
  • createElement函数对key和ref等特殊的props进行处理,并获取defaultProps对默认props进行赋值,并且对传入的孩子节点进行处理,最终构造成一个虚拟DOM对象
  • ReactDOM.render将生成好的虚拟DOM渲染到指定容器上,其中采用了批处理、事务等机制并且对特定浏览器进行了性能优化,最终转换为真实DOM

4.React Router的理解,原理?常用的Router组件有哪些?

  • 路由的本质就是页面的URL发生改变时,页面的显示结果可以根据URL的变化而变化,但是页面不会刷新
  • react-router主要分成了几个不同的包(这一块先不写了)
  • 常用router组件:
    • BrowserRouter、HashRouter : 路由模式history,hash
    • route: Route用于路径的匹配,然后进行组件的渲染
    • Link、NavLink: 通常路径的跳转是使用Link组件 NavLink是在Link基础之上增加了一些样式属性,例如组件被选中时,发生样式变化 ( activeStyle , activeClassName )
    • redirect:路由重定向
    • switch: swich组件的作用适用于当匹配到第一个组件的时候,后面的组件就不应该继续匹配

5.react生命周期

  • 组件挂载时
    当组件实例被创建并插入DOM时,其生命周期调用顺序如下:

    constructor()
    static getDerivedStateFromProps()
    render()
    componentDidMount()

  • 组件更新时
    当组件的props或state发生变化时会触发更新。组件更新的生命周期调用顺序如下:

    static getDerivedStateFromProps()
    shouldComponentUpdate()
    render()
    getSnapshotBeforeUpdate()
    componentDidUpdate()

  • When the component is unloaded,
    the following method will be called when the component is removed from the DOM

    componentWillUnmount()

6. What does the new react life cycle replace? Why?

React's new life cycle method is mainly designed to support three new concepts in the Fiber architecture: fiber nodes, asynchronous rendering, and interruptibility

  • getDerivedStateFromProps(static method) replaces componentWillMount and componentWillReceiveProps

  • getSnapshotBeforeUpdate replaces componentWillUpdate

  • Components are prohibited from accessing this.props in getDerivedStateFromProps. Since this.propsmay change at any time, the calculated state object may be the same as the old state object, resulting in invalid state updates and unnecessary component re-rendering. In getDerivedStateFromPropsthe method you should always use the in parameter nextPropsinstead of this.props. This ensures that the calculation of the component state is based on the latest props, thereby avoiding invalid state updates and rendering performance problems.

  • renderThe getSnapshotBeforeUpdate method is called after the method of the component is called, but before updating the DOM, that is to say, what is read in getSnapshotBeforeUpdate DOM 元素信息can be guaranteed to be consistent with that in componentDidUpdate.

7. Understanding of Fiber architecture? What problem did it solve?

Before React 16, the update of VirtualDOM was realized Stack架构, that is, the circular recursion method. However, this comparison method has obvious defects, that is, once the task starts, it cannot be interrupted. If the number of components in the application is relatively large, the level of VirtualDOM will be relatively deep, and the result is that the main thread is occupied for a long time. This blocks rendering and causes stuttering.

fiber: In order to avoid problems such as lag, we must ensure that the calculation time does not exceed 16ms when performing the update operation. 16msIf it exceeds 16ms, we need to pause first, let the browser render, and then continue to perform update calculations. The Fiber architecture was 可中断渲染created to support " ".解决了react在渲染大量dom节点出现丢帧的问题

The interaction process between React Fiber and the browser is shown in the figure below.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-4G89UyXp-1686967105051) (C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\ 1685850448945.png)]

  • From an architectural point of view: fiber is a rewrite of the core algorithm of react (reconciliation process)
  • From the perspective of coding: fiber is a kind of internal definition of react 数据结构, which is the node unit of fiber tree structure, virtual dom under the new architecture of react16
  • Main operations:
    • A priority is added for each, and tasks with higher priority can interrupt lower-priority tasks. Then restart, pay attention to re-execute tasks with low priority
    • Added asynchronous tasks, call requestIdleCallback api, execute when the browser is idle
    • The dom diff tree has become a linked list. One dom corresponds to two fibers (one linked list) and two queues. This is to find the interrupted task and re-execute it.

In the Fiber architecture, React divides the component update process into two phases: reconciliation and commit. The reconciliation stage is mainly responsible for calculating the updated Virtual DOM tree and determining which components need to be re-rendered, while the commit stage is responsible for mapping the changes of the Virtual DOM tree to the real DOM.

Summary: Compared with the traditional Stack architecture, Fiber divides the work into multiple work units. After each work unit is executed, it decides whether to give up control to the browser to perform rendering according to the remaining time. And it sets the priority of each unit of work, suspends, reuses and aborts units of work. Each fiber node is a node on the fiber tree, connected by children, brothers and return references to form a complete fiber tree.

8. Understanding and usage scenarios of react stateful components and stateless components? ,

  • stateful components
    • Features:
      • It is a class component
        with inheritance
        , you can use this,
        you can use the life cycle of react, it
        is used more frequently, and it is easy to trigger the life cycle hook function frequently , affecting the performance.
        Internal use state, maintain the change of its own state, stateful components according to the props passed in by external components and themselves state for rendering
    • scenes to be used:
      • Those that need to use state
        need to use state to operate components (stateless components can also implement the new version of react hooks)
    • Summary:
      Class components can maintain their own state variables, that is, the state of the component. Class components also have different life cycle methods, which allow developers to do more with components at different stages of the component (mounting, updating, and uninstalling). control. Class components can act as both stateless and stateful components. When a class component does not need to manage its own state, it can also be called a stateless component.
  • stateless components
    • Features:
      • The state that does not depend on itself
        can be a class component or a function component.
        You can completely avoid using the this keyword (because you use arrow function events without binding)
        and have higher performance. When you don’t need to use lifecycle hooks, you should use them first. Stateless function component The
        component does not maintain state inside the component, and only renders the component according to the props passed in by the external component. When the props changes, the component re-renders
    • scenes to be used
      • Components do not need to manage state, pure display
    • Advantages:
      Simplify code, focus on render
      components do not need to be instantiated, no life cycle, improve performance, output (rendering) only depends on input (properties), no side effects Decoupling
      and separation of views and data
    • Disadvantages:
      Unable to use ref
      without life cycle method
      Unable to control re-rendering of components, because shouldComponentUpdate method cannot be used, when the component receives new properties, it will re-render

9. React's event synthesis?

  • All events are delegated id = rootin the DOM element (many on the Internet say it is in document, 17the version is not);
  • The event monitoring of all nodes in the application is actually id = roottriggered in the DOM element;
  • ReactImplemented a set of event bubbling capture mechanism by itself;
  • ReactSynthetic events are implemented SyntheticEvent;
  • ReactThe event pool is no longer used in 17the version (many on the Internet say that the object pool is used to manage the creation and destruction of synthetic event objects, which is 16the version and before);
  • Once the event id = rootis delegated in the DOM element, it is actually triggered all the time, but the corresponding callback function is not bound;

10. How to communicate between React components?

  1. 父组件向子组件通讯:
    父组件可以向子组件传入props的方式,向子组件进行通讯。
  2. 子组件向父组件通讯:
    props+回调的方式,父组件向子组件传递props进行通讯,此props为作用域为父组件自身的函数,子组件调用该函数,将子组件想要传递的信息,作为参数,传递到⽗组件的作⽤域中。
  3. 兄弟组件通信:
    兄弟组件之间的传递,则父组件作为中间层来实现数据的互通,通过使用父组件传递
    例:组件A – 传值 --> 父组件 – 传值 --> 组件B
  4. 跨层级通讯:
    Context 设计⽬的是为了共享那些对于⼀个
    组件树⽽⾔是“全局”的数据,
    使用context提供了组件之间通讯的一种方式,可以共享数据,其他数据都能读取对应的数据
    例如当前认证的⽤户、主题或⾸选语⾔,对于跨越多层的全局数据通过 Context 通信再适合不过。
  5. 发布订阅者模式:
    发布者发布事件,订阅者监听事件并做出反应,我们可以通过引⼊event模块进⾏通信。
  6. 全局状态管理工具:
    借助Redux或者Mobx等全局状态管理⼯具进⾏通信,这种⼯具会维护⼀个全局状态中⼼Store,并根据不同的事件产⽣新的状态。

11.React服务端渲染怎么做?原理是什么?

  • 服务端渲染(SSR): 指由服务侧完成页面的 HTML 结构拼接的页面处理技术,发送到浏览器,然后为其绑定状态与事件,成为完全可交互页面的过程
  • 服务端渲染解决的问题:1.SEO由于搜索引擎爬虫抓取工具可以直接查看完全渲染的页面 2.加速首屏加载,解决首屏白屏问题
  • React如何做服务端渲染?
    • 手动搭建SSR框架
    • 使用成熟的SSR框架,如next.js
  • 实现原理:
    • node server 接收客户端请求,得到当前的请求url 路径,然后在已有的路由表内查找到对应的组件,拿到需要请求的数据,将数据作为 propscontext或者store 形式传入组件
    • 然后基于 react 内置的服务端渲染方法 renderToString()把组件渲染为 html字符串在把最终的 html 进行输出前需要将数据注入到浏览器端
    • 浏览器开始进行渲染和节点对比,然后执行完成组件内事件绑定和一些交互,浏览器重用了服务端输出的 html 节点,整个流程结束

12.使用 React hooks 怎么实现类里面的所有生命周期?

  • 在 React 16.8 之前,函数组件也称为无状态组件

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wyoi6A3F-1686967105051)(C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\1682042087354.png)]

13.React事件和原生事件的执行顺序

  • 为什么会有合成事件:
    • 在传统的事件里,不同的浏览器需要兼容不同的写法,在合成事件中React提供统一的事件对象,抹平了浏览器的兼容性差异
    • React通过顶层监听的形式,通过事件委托的方式来统一管理所有的事件,可以在事件上区分事件优先级,优化用户体验。React在合成事件上对于16版本和17`版本的合成事件有很大不同
  • 执行顺序总结:
    • 16版本先执行原生事件,当冒泡到document时,统一执行合成事件,
    • 17版本在原生事件执行前先执行合成事件捕获阶段,原生事件执行完毕执行冒泡阶段的合成事件,通过根节点来管理所有的事件,原生的阻止事件流会阻断合成事件的执行,合成事件阻止后也会影响到后续的原生执行

14.为什么react元素有一个$$type属性?

目的是为了防止 XSS 攻击。因为 Synbol 无法被序列化,所以 React 可以通过有没有 $$typeof 属性来断出当前的 element 对象是从数据库来的还是自己生成的。如果没有 $$typeof 这个属性,react 会拒绝处理该元素。

15.setState 是同步,还是异步的?

  • react18之前:setState在不同情况下可以表现为异步或同步。在Promise的状态更新、js原生事件、setTimeout、setInterval…中是同步的。在react的合成事件中,是异步的。
  • react18之后: setState都会表现为异步(即批处理)。
  • 解释react18之前:
    • 原因: 在React的setState函数实现中,会根据一个变量isBatchingUpdates判断是直接更新this.state还是放到队列中回头再说,而isBatchingUpdates默认是false,也就表示setState会同步更新this.state,但是,有一个函数batchedUpdates,这个函数会把isBatchingUpdates修改为true,而当React在调用事件处理函数之前就会调用这个batchedUpdates,造成的后果,就是由React控制的事件处理过程setState不会同步更新this.state。

16.如何让 useEffect 支持 async/await?

  • 为什么不支持?
    • effect functionShould return a destruction function ( returnreturned cleanupfunction), if useEffectthe first parameter is passed in async, the return value will become Promise, which will cause reactan error when calling the destruction function
  • How does useEffect support async/await?
    • Create an asynchronous function ( async...awaitway), and execute that function.

17. What performance optimizations can be done in React?

  • Use pure components – Pure components are those that do not depend on external state or references

  • shouldComponentUpdate optimization

  • Don't use inline function definitions (if we use inline functions, rendera new function instance will be created every time the " " function is called)

    function MyButton(props) {
      return (
        <button onClick={() => console.log('Button clicked!')}>
          {props.label}
        </button>
      );
    }
    
    
  • Avoid using inline style attributes;

  • Use immutable immutable data. When using reference types in our project, in order to avoid the impact on the original data, it is generally recommended to use shallowCopy and deepCopy to process the data, but this will cause waste of CPU and memory, so it is recommended to use immutable

    • advantage:
      • Reduces the complexity of variable
      • Save memory, immutable uses structure sharing to reuse memory as much as possible, and objects that are not referenced will be garbage collected
      • There will be no concurrency issues (since the data itself is immutable)
      • Embrace functional programming
  • Set a unique key for the subcomponent, because in the diff algorithm, the key will be used as the unique identifier to optimize rendering

  • Use React.memofor component memory ( React.memoa high-level component), for the same input, do not repeat execution;

  • useCallbackUse and in the function component useMemoto optimize the component. If there is no change in the dependency, it will not be executed repeatedly

  • Routing lazy loading

18. What is the difference between react and vue?

  • the difference:
    • React 的思路是 HTML in JavaScript 通过 JavaScript 来生成 HTML,所以设计了 JSX 语法,还有通过 JS 来操作 CSS
    • Vue 是把 HTML,CSS,JavaScript 组合到一起,用各自的处理方式,Vue 有单文件组件,可以把 HTML、CSS、JS 写到一个文件中,HTML 提供了模板引擎来处理。
    • React 整体是函数式的思想,在 React 中是单向数据流,推崇结合 immutable 来实现数据不可变。
    • Vue 的思想是响应式的,也就是基于是数据可变的,通过对每一个属性建立 Watcher 来监听,当属性变化的时候,响应式的更新对应的虚拟 DOM。
    • React 的性能优化需要手动去做,而Vue的性能优化是自动的,但是Vue的响应式机制也有问题,就是当 state 特别多的时候,Watcher 会很多,会导致卡顿。
  • 共同点:
    • React 与 Vue 存在很多共同点,例如他们都是 JavaScript 的 UI 框架,组件化开发,单项数据流,声明式编程,虚拟dom
  • 优势:
    • React
      • 灵活性和响应性:它提供最大的灵活性和响应能力。
      • 丰富的JavaScript库:来自世界各地的贡献者正在努力添加更多功能。
      • 可扩展性:由于其灵活的结构和可扩展性,React已被证明对大型应用程序更好。
      • 不断发展: React得到了Facebook专业开发人员的支持,他们不断寻找改进方法。
      • Web或移动平台: React提供React Native平台,可通过相同的React组件模型为iOS和Android开发本机呈现的应用程序。
    • Vue
      • 易于使用: Vue.js包含基于HTML的标准模板,可以更轻松地使用和修改现有应用程序。
      • 更顺畅的集成:无论是单页应用程序还是复杂的Web界面,Vue.js都可以更平滑地集成更小的部件,而不会对整个系统产生任何影响。
      • 更好的性能,更小的尺寸:它占用更少的空间,并且往往比其他框架提供更好的性能。
      • 精心编写的文档:通过详细的文档提供简单的学习曲线,无需额外的知识; HTML和JavaScript将完成工作。
      • 适应性:整体声音设计和架构使其成为一种流行的JavaScript框架。
      • 它提供无障碍的迁移,简单有效的结构和可重用的模板。
  • 总结:
    • Vue 的响应式机制也有问题,当 state 特别多的时候,Watcher 会很多,会导致卡顿,所以大型应用(状态特别多的)一般用 React,更加可控。
    • 对于易用性来说,VUE 是更容易上手的,对于项目来说新人更容易接手。

19.React render方法的原理,在什么时候会触发?

原理:
在类组件中render函数指的就是render方法;而在函数组件中,指的就是整个函数组件
render函数中的jsx语句会被编译成我们熟悉的js代码,在render过程中,react将新调用的render函数返回的树与旧版本的树进行比较,这一步是决定如何更新 DOM 的必要步骤,然后进行 diff 比较,更新dom树
触发机:
类组件调用 setState 修改状态
函数组件通过useState hook修改状态
一旦执行了setState就会执行render方法,useState 会判断当前值有无发生改变确定是否执行render方法,一旦父组件发生渲染,子组件也会渲染

20.React Hooks 在使用上有哪些限制?

  • 不要在循环、条件或嵌套函数中调用 Hook;
  • 在 React 的函数组件中调用 Hook。

21.React Hooks概述及常用的Hooks介绍?

Hooks是React 16.8版本引入的新特性,它为函数组件添加了一些类似于类组件中的状态和生命周期方法的功能

  • useState:用于在函数组件中添加状态管理功能。它返回一个由当前状态值和更新函数组成的数组,我们可以通过该数组来获取和更新状态的值。
  • useEffect:用于执行副作用操作,例如订阅事件、修改DOM等。它接受一个函数作为参数,该函数将在每次渲染完成后执行。
  • useContext:用于在组件间共享数据,它接受一个上下文对象作为参数,然后返回该上下文对象中提供的数据。
  • useReducer:用于对复杂状态进行管理。它接受一个reducer函数和初始状态作为参数,并返回一个由当前状态值和dispatch函数组成的数组。
  • useCallback:用于缓存函数以提高性能,类似于React.memo。
  • useMemo:用于缓存计算结果以提高性能,类似于记忆函数。
  • useRef:用于引用DOM节点或保存任意可变值,它返回一个可变的ref对象。

22.说说React生命周期中有哪些坑?如何避免?

  • getDerivedStateFromProps 容易编写反模式代码,使受控组件和非受控组件区分模糊
  • componentWillMountReact 中已被标记弃用,不推荐使用,主要的原因是因为新的异步架构会导致它被多次调用,所以网络请求以及事件绑定应该放到 componentDidMount
  • componentWillReceiveProps 同样也被标记弃用,被 getDerivedStateFromProps 所取代,主要原因是性能问题。
  • shouldComponentUpdate 通过返回 true 或者 false 来确定是否需要触发新的渲染。主要用于性能优化。
  • componentWillUpdate 同样是由于新的异步渲染机制,而被标记废弃,不推荐使用,原先的逻辑可结合 getSnapshotBeforeUpdatecomponentDidUpdate 改造使用。
  • 如果在 componentWillUnmount 函数中忘记解除事件绑定,取消定时器等清理操作,容易引发 bug
  • 如果没有添加错误边界处理,当渲染发生异常时,用户将会看到一个无法操作的白屏,所以一定要添加。

23.说说Real diff算法是怎么运作的?

  • DiffAlgorithm is DOMan inevitable result of virtualization, it is through DOMthe comparison of old and new, it will need to update the content partially without updating the page
  • DiffThe algorithm follows the principle of depth-first and same-level comparison
  • reactThe algorithm diffmainly follows the strategy of three levels:
    tree level : cross-level operations of DOM nodes are not optimized, only nodes of the same level are compared, only delete and create operations are performed, and there is no move operation.
    component level : if it is the same type of component, then It will continue to perform diff operations, if not, delete all child nodes under the component directly, and create a new
    element level : For comparing nodes at the same level, each node is uniquely keyidentified at the corresponding level, and is known through the key Node changes, move the old set node position, update to the new set node position

24. What does setState do in the reconciliation phase?

  • setStateAfter the function is called in the code , Reactthe incoming parameter object will be merged with the current state of the component, and then the so-called reconciliation process ( Reconciliation) will be triggered.
  • After the reconciliation process, the element tree Reactwill be constructed according to the new state in a relatively efficient manner Reactand the entire UI interface will be re-rendered;
  • After Reactgetting the element tree, Reactit will automatically calculate the node difference between the new tree and the old tree, and then minimize the re-rendering of the interface according to the difference;
  • In the difference calculation algorithm, Reactit is relatively accurate to know which positions have changed and how they should be changed, which ensures on-demand updates instead of all re-rendering.

25. What are the principles of using redux?

  • Single data source: The global state of the entire application is stored in an object tree, and this object tree only exists in the only store.
  • State is read-only: the only way to change the state is to fire an action, which is a plain object describing what happened.
  • Use pure functions to perform modifications: To describe how an action changes the state tree, you need to write pure reducers.

26. Talk about the realization principle of redux, and write the core code?

  • Put the state of the application in a unified way andstate manage it .storestate
  • reducerThe function is to return a new one stateto update the storeused one state.
  • According reduxto the principle, UI层each state change should be triggered by actiongo, actionpassed into the corresponding reducer, and returned to reducera new stateupdate , thus completing a state updatestorestate
  • subscribeIt is a storesubscription listener function , and these subscribed listener functions are dipatchexecuted sequentially after each initiation
  • dispatchYou can add middleware to rewrite the submitted
    core API
  • createStoreCreate repository, accepts reduceras argument
  • bindActionCreatorThe relationship between binding store.dispatchandaction
  • combineReducersmerge multiplereducers
  • applyMiddlewareMiddleware for the onion model, between dispatchand actionbetween, rewritedispatch
  • composeIntegrate multiple middleware

27. Understanding of Redux middleware? principle? What are the commonly used middleware?

Redux中,中间件就是放在就是在dispatch过程,在分发action进行拦截处理, 其本质上一个函数,对store.dispatch方法进行了改造,在发出 Action 和执行 Reducer 这两步之间,添加了其他功能

实现原理:

  • applyMiddlewares的源码 中我们可以看到 ,所有中间件被放进了一个数组chain,然后嵌套执行,最后执行store.dispatch。可以看到,中间件内部(middlewareAPI)可以拿到getStatedispatch这两个方法

常用中间件:

  • redux-thunk:用于异步操作
  • redux-logger:用于日志记录

28.Redux 和 Vuex 有什么区别,它们有什么共同思想吗?

  • 相同点:
    • state 共享数据
    • 流程一致:定义全局state,触发,修改state
    • 原理相似,通过全局注入store。
  • 不同点:
    • 实现原理:
      • Redux 使用的是不可变数据,而Vuex的数据是可变的。Redux每次都是用新的state替换旧的state,而Vuex是直接修改
      • Redux 在检测数据变化的时候,是通过 diff 的方式比较差异的,而Vuex其实和Vue的原理一样,是通过 getter/setter来比较的
    • 表现层:
      • vuex定义了state、getter、mutation、action四个对象;redux定义了state、reducer、action。
      • vuex中state统一存放,方便理解;reduxstate依赖所有reducer的初始值
      • vuex有getter,目的是快捷得到state;redux没有这层,react-redux mapStateToProps参数做了这个工作。
      • vuex中mutation只是单纯赋值(很浅的一层);redux中reducer只是单纯设置新state(很浅的一层)。他俩作用类似,但书写方式不同
      • vuex中action有较为复杂的异步ajax请求;redux中action中可简单可复杂,简单就直接发送数据对象({type:xxx, your-data}),复杂需要调用异步ajax(依赖redux-thunk插件)。
      • vuex触发方式有两种commit同步和dispatch异步;redux同步和异步都使用dispatch
  • 共同思想:
    • 单一的数据源
    • 变化可以预测

29.props和state相同点和不同点?

不同点:
props是只读的,只能由父组件传递给子组件,而不能在子组件中修改。而state是可变的,在组件内部可以通过setState方法来修改其值
相同点:
1.props和state都会触发渲染更新

​ 2.props和state都是纯JS对象(用typeof来判断,结果都是object)

30.shouldComponentUpdate有什么作用?

shouldComponentUpdate () 可以理解为是否触发渲染的阀门,当状态发生改变时会走到该生命周期,shouldComponentUpdate接收两个参数props,state分别是更新前和更新后的状态,可以判断前后是否发生改变返回true和false,来决定是否往下执行

31.React的props.children使用map函数来遍历会收到异常显示,为什么?应该 如何遍历

原因:在react.js中props.children不一定是数组

  • 当前组件没有子节点 undefined
  • 有一个子节点 object
  • 多个子节点 array

react资深提供了一个react.children.map()方法,可以安全遍历子节点对象。

32.谈谈你对immutable.js的理解?

Immutable.js采用了 持久化数据结构 ,保证每一个对象都是不可变的,任何添加、修改、删除等操作都会生成一个新的对象,且通过 结构共享 等方式大幅提高性能

33. Redux principle, workflow and application, three principles

Redux: redux is a javascript library dedicated to centralized management state , and it is also 不是a react plug-in library.

The three cores of redux:

  • Actions
    The literal translation of actions in English means action and action, so we can guess that it means "how to do it". Simply put, actions are an object, and there are two attributes in actions: type and data: type:
    identification Attribute, the value is a string and unique, required attribute (what you want to do
    data: data attribute, the value is any type, optional attribute (the data you want to do

    Then let's give a simple example: For example, you can perform operations such as adding 1 and subtracting 2 with a calculator, then the operations of addition, subtraction, multiplication and division are your type, and numbers are your data

  • There is only one store
    , and it is equivalent to a supreme conductor. He is responsible for handing over the action to the corresponding reducer for execution, that is to say, the object that links state, action and reducer.

  • reducer
    The reducer is used to complete the action sent by the store and return the result to the store. It receives two parameters preState (old state) and action (action) and returns a newState (new state).

Workflow: When the component needs to change the data in the store, tell the action to generate an action object, distribute the object to the store through dispatch, the store binds the reducer to be used, and then distributes the action to the corresponding reducer to execute the corresponding logic. 数据覆盖, and then render the store data

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-srPGmnk2-1686967105052)(C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\1685666639607.png)]

三大原则

唯一数据源(state)

数据源(state)只读

通过纯函数(pure function)改变数据源(state)

34.react-redux原理,工作流程

react-redux实现过程

react-redux执行流程详解:

初始化阶段:

  • 创建 Redux store 对象,并将 Reducer 传入 createStore 函数中。
  • 创建一个 Provider 组件,并将 Redux store 对象作为 Provider 组件的 props 传入其中。
  • 将应用根组件包装在 Provider 组件中,并渲染整个应用。

运行阶段:

  • 使用 connect 函数将组件与 Redux 中的 state 和 action creators 相连接,并将它们转化为组件的 props 属性
import { connect } from 'react-redux';
import { addToCart } from '../actions';

const Product = ({ product, addToCart }) => (
 <div>
   <h3>{product.name}</h3>
   <button onClick={() => addToCart(product)}>Add to cart</button>
 </div>
);

const mapDispatchToProps = {
 addToCart,
};

export default connect(null, mapDispatchToProps)(Product);

更新阶段:

  • 在 Store 的 dispatch 方法中,执行 action 并更新 Store 中的 state。
  • React-Redux 根据 Store 中的新状态,检查哪些组件的 props 发生了变化。
  • 对于发生变化的组件,React-Redux 将触发相关的生命周期方法和 render 方法进行重新渲染。

工作流程:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OaD98GCF-1686967105053)(C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\1685667792598.png)]

35.react组件通讯的context

使用步骤:

  • 在顶层组件中创建一个 context 对象,并将需要共享的数据挂载到该对象上

    const MyContext = React.createContext(defaultValue);
    
  • 在顶层组件的 render 方法中,使用 MyContext.Provider 组件来包裹整个应用程序,并将共享的数据传递给 value 属性

    <MyContext.Provider value={sharedData}>
        <App />
    </MyContext.Provider>
    
  • 在需要使用共享数据的组件中,使用 MyContext.Consumer 组件来接收 context 的 value 属性,并在 Consumer 的子元素中使用这些数据

    <MyContext.Consumer>
        {sharedData => (
            // 此处可以使用 sharedData 来操作共享数据
        )}
    </MyContext.Consumer>
    

36.react-redux中 Provider 组件实现原理

React-Redux 中的 Provider 组件是一个 React 组件,它使用了 React 的 Context API 来实现数据的传递。Provider 组件提供一个 context 对象,它可以让嵌套在它内部的子组件都可以访问到这个 context 对象,并且可以通过它来获取到 Redux store 中的数据。

37.react-redux中Connect原理

connect 函数是将 React 组件与 Redux Store 进行连接的重要方法。它接收两个函数作为参数,并返回一个高阶组件,通过这个高阶组件可以将 Redux Store 和 React 组件关联起来。 (实现容器组件包裹ui组件)

在原应用组件上包裹一层,使原来整个应用成为Provider的子组件,接收Redux的store作为props,通过context对象传递给子孙组件上的connect,它真正连接 Redux 和 React,它包在我们的容器组件的外一层,它接收上面 Provider 提供的 store 里面的 state 和 dispatch,传给一个构造函数,返回一个对象,以属性形式传给我们的容器组件。

//其中 mapStateToProps 和 mapDispatchToProps 是将 Store 和 action creator 映射到组件的 props 上的函数。
connect(mapStateToProps, mapDispatchToProps)(Product);

38.react-toolkit

react-toolkit是一个官方维护的包含多个有用工具的 Redux 库,旨在使 React 和 Redux 的开发变得更加简单、高效和直观

  1. 简化 Redux 工作流

redux-toolkitProvides a new way to write Redux applications that embraces common Redux patterns and simplifies them by encapsulating boilerplate code. This allows developers to focus more on implementing business logic without having to care about lower-level details.

  1. Built-in common middleware

redux-toolkitContains several middleware commonly used in Redux applications, such as redux-thunkmiddleware, redux-sagamiddleware, and redux-loggermiddleware, so that developers can easily use and configure these middleware.

  1. enforce immutability

redux-toolkitThe createSlicefunction will automatically update the state with immutability when creating the reducer, which avoids potential errors caused by directly modifying the state.

  1. Automatically generate Redux action types

redux-toolkitA function is provided createSliceto create a reducer, which will also automatically create a string constant for each action type, avoiding the redundant code caused by manually writing these constants.

  1. manage side effects

redux-toolkitThe function is provided createAsyncThunkto create actions with asynchronous side effects, which automatically handles the asynchronous process and can track the progress and results of each asynchronous operation in state.

39. What is the usage of React.memo() and useMemo(), and what are the differences?

React.memoIt is a high-level component that can use a pure function component. When the props of the component do not change, it will directly reuse the rendering result of the component, thus avoiding unnecessary rendering.

//当 MyComponent 的 text 属性没有变化时,MemoizedComponent 就会复用之前的渲染结果,而不会重新渲染。
function MyComponent(props) {
  return <div>{props.text}</div>;
}
const MemoizedComponent = React.memo(MyComponent);

useMemoIs a Hook that can be used to cache calculation results to avoid repeated calculations. When the incoming dependencies have not changed, the cached results are returned directly.

//如果 calculate 方法比较耗时,为了避免不必要的计算,我们可以使用 useMemo 来缓存计算结果:
function MyComponent({ a, b }) {
  const result = useMemo(() => calculate(a, b), [a, b]);
  return <div>{result}</div>;
}

the difference:

React.memo​and useMemocan be used to optimize the performance of React applications, but their optimization objects and optimization methods are different. React.memoImproves performance by avoiding unnecessary rendering of components, and useMemoimproves performance by avoiding double calculations. In actual development, it is necessary to select a suitable optimization method according to specific scenarios and requirements.

40. The difference between usecallback and usememo

useCallbackUsed to cache functions to avoid unnecessary function creation and rendering. When the dependencies change, a new function reference is returned, otherwise the previously cached function reference is returned directly.

const memoizedCallback = useCallback(() => {
  doSomething(a, b);
}, [a, b]);

useMemoUsed to cache calculation results to avoid repeated calculation and rendering. When dependencies change, it will recalculate and return the new computed result

const memoizedValue = useMemo(() => {
  return heavyComputation(a, b);
}, [a, b]);

useCallbackImproves performance by avoiding function creation and rendering, and useMemoimproves performance by avoiding double calculation and rendering

41. React uses ref

A ref is a way to access a reference to a DOM element or component instance.

字符串回调

class MyComponent extends React.Component {
  componentDidMount() {
    console.log(this.refs.myInput);
    // 输出:<input type="text" />
  }
  render() {
    return <input type="text" ref="myInput" />;
  }
}

函数回调

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = null;
  }
  componentDidMount() {
    console.log(this.myRef);
    // 输出:<input type="text" />
  }
  render() {
    return <input type="text" ref={node => this.myRef = node} />;
  }
}

React.createRef

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  componentDidMount() {
    console.log(this.myRef.current);
    // 输出:<input type="text" />
  }
  render() {
    return <input type="text" ref={this.myRef} />;
  }
}

42. Why loops and judgments cannot use hooks

reason:

​Block-level scopes such as loops and conditional statements will affect the number and order of Hooks calls, thus destroying the dependencies and rendering logic inside React, resulting in unexpected errors in components. Therefore, in order to ensure that components can be rendered and updated normally, we need to follow the usage specification of React Hooks and call Hooks in the top-level scope.

43.React implements excessive animation

Use a third-party library: React Transition Group to learn more about transition animation

Note: The class naming method in CSSTransitionclassNames

44. Implementation principle of react lazy loading

React's lazy loading implementation principle is mainly based on ES6 import()functions and React lazyfunctions.

import React, { lazy, Suspense } from "react";

const LazyComponent = lazy(() => import("./LazyComponent"));

function App() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <LazyComponent />
      </Suspense>
    </div>
  );
}

When we use lazythe function, React will dynamically create a new component at runtime. This new component inherits all the properties and methods of the original component, and its render method is rewritten as an asynchronous function. When this new component needs to be rendered, React will automatically trigger its render method, which asynchronously loads the original component's code and renders it on the page.

This involves import()the function in ES6, which is an asynchronous function used to dynamically load JavaScript modules. import()The function will return a Promise object. When the module is loaded, the Promise object will be resolved. We can get the default export object of the module through the then method.

45.immutable

Immutable is a JavaScript library that provides some data structures and APIs that make creation 不可变数据possible. Using Immutable in React can bring the following benefits:

  • Performance optimization: The Virtual DOM technology used in React will perform frequent comparison and update operations, and immutable data can reduce the number of nodes that need to be updated, thereby improving the performance and response speed of the application.
  • Easy to manage state: The state in React applications is usually very complex. Using immutable data can manage the state more conveniently and avoid side effects caused by state modification.
  • Concurrency safety: In a high-concurrency environment, using immutable data can reduce data competition and lock competition, and improve concurrency safety performance.

Immutable creates an immutable data type. If you want to modify it, you can only create a new variable through data coverage to optimize the performance of react.

46.Why does useState return an array instead of an object

Reason: The React team believes that using arrays allows for better flexibility and ease of use

advantage:

  • No need to name: When using arrays, we can use the array destructuring syntax to name state variables and modify functions, and we don't need to consider issues such as naming conflicts.
  • Direct modification: After using array destructuring, we can directly modify the array elements without calling a method or property in the object again.
  • Easy to expand: In future versions, React may also add more state-related Hooks, and using an array can make it easier to add new Hooks to the existing syntax

47. Why can't class components use hooks

Hooks is designed based on functional programming ideas and does not support some features of class components. However, React provides some methods that allow developers to use some functions of Hooks in class components, or convert class components into function components to use Hooks.

48. The difference between redux-thunk and redux-saga

redux-thunkThe idea behind the design is to encapsulate asynchronous logic into a "thunk" function that takes a method dispatchas an argument and returns a function with a callback function. This callback function is called after the asynchronous operation is completed, and then dispatchan action is triggered through the method to update the data in the Redux store. redux-thunkSuitable for handling simple asynchronous logic, such as sending AJAX requests or getting local storage data. no extension api

redux-sagaAnother design idea is adopted, which uses the generator function of ES6 to realize the management of asynchronous logic. In redux-saga, use the generator function to define a saga, which can monitor one or more actions, and perform some side effects after the corresponding actions are triggered, such as sending AJAX requests, triggering other actions, and so on. redux-sagaIt also provides some auxiliary functions and features (api), such as takeLatest, put, calletc., which make it easier for developers to manage asynchronous processes, handle errors and cancel requests, etc.

49. Reasons and principles for using react synthetic events

Explore Synthetic Events

React synthetic event (SyntheticEvent) is an event object that React simulates all the capabilities of native DOM events

Reason for use:

  • Compatible with browsers to achieve better cross-platform

    ​ React uses 顶层事件代理a mechanism that can ensure bubbling consistency and can be executed across browsers. The synthetic events provided by React are used to smooth out the differences between different browser event objects, and simulate different platform events to simulate synthetic events.

  • avoid garbage collection

    ​ Event objects may be frequently created and recycled, so React introduced 事件池to acquire or release event objects in the event pool. That is, the React event object will not be released, but stored in an array 数组. When the event is triggered, it will be popped out of this array to avoid frequent creation and destruction (garbage collection).

  • Facilitate unified event management and transaction mechanism

principle:

  • event binding
    • Before React17, React delegated events to the document. React17 and later versions no longer delegate events to the document, but to the mounted container
    • Native events and synthetic events are actually related through a module called EventPlugin. Each plug-in only handles the corresponding synthetic event. For example, the onClick event corresponds to the SimpleEventPlugin plug-in, so that React will load these plug-ins at the beginning Come in, initialize some global objects through the plug-in, for example, one of the objects is registrationNameDependencies, which defines the correspondence between synthetic events and native events
  • event trigger
    • The event trigger will execute the dispatchEvent function. When the event is triggered, all the parent elements of the current element will be processed and constructed into a synthetic object, and the synthetic event will be stored in the eventQueue once, and the eventQueue will be traversed to simulate the capture and bubbling phases, and then triggered in turn by the runEventsInBatch method Call the listener event of each item

50. React event proxy mechanism

React does not bind all handlers directly to real nodes. Instead, bind all events to the outermost layer of the structure, and use a unified event listener, which maintains a mapping to save the event listening and processing functions inside all components.

  • All events are delegated id = rootin the DOM element (many on the Internet say it is in document, 17the version is not);
  • The event monitoring of all nodes in the application is actually id = roottriggered in the DOM element;
  • ReactImplemented a set of event bubbling capture mechanism by itself;
  • ReactSynthetic events are implemented SyntheticEvent;
  • ReactThe event pool is no longer used in 17the version (many on the Internet say that the object pool is used to manage the creation and destruction of synthetic event objects, which is 16the version and before);
  • Once the event id = rootis delegated in the DOM element, it is actually triggered all the time, but the corresponding callback function is not bound;

51. Execution order of React events and native events

import React, { useRef, useEffect } from "react";
import "./styles.css";

const logFunc = (target, isSynthesizer, isCapture = false) => {
    const info = `${isSynthesizer ? "合成" : "原生"}事件,${
        isCapture ? "捕获" : "冒泡"}阶段,${target}元素执行了`;
    
    console.log(info);
};

const batchManageEvent = (targets, funcs, isRemove = false) => {
    targets.forEach((target, targetIndex) => {
        funcs[targetIndex].forEach((func, funcIndex) => {
            target[isRemove ? "removeEventListener" : "addEventListener"](
                "click",
                func,
                !funcIndex
            );
        });
    });
};

export default function App() {
    const divDom = useRef();
    const h1Dom = useRef();
    useEffect(() => {
    
        const docClickCapFunc = () => logFunc("document", false, true);
        const divClickCapFunc = () => logFunc("div", false, true);
        const h1ClickCapFunc = () => logFunc("h1", false, true);
        const docClickFunc = () => logFunc("document", false);
        const divClickFunc = () => logFunc("div", false);
        const h1ClickFunc = () => logFunc("h1", false);

        batchManageEvent(
            [document, divDom.current, h1Dom.current],
            [
                [docClickCapFunc, docClickFunc],
                [divClickCapFunc, divClickFunc],
                [h1ClickCapFunc, h1ClickFunc]
            ]
        );

        return () => {
            batchManageEvent(
                   [document, divDom.current, h1Dom.current],
                [
                    [docClickCapFunc, docClickFunc],
                    [divClickCapFunc, divClickFunc],
                    [h1ClickCapFunc, h1ClickFunc]
                ],
                true
            );
        };
    }, []);

    return (
        <div
          ref={divDom}
          className="App1"
          onClickCapture={() => logFunc("div", true, true)}
          onClick={() => logFunc("div", true)}
        >
          <h1
            ref={h1Dom}
            onClickCapture={() => logFunc("h1", true, true)}
            onClick={() => logFunc("h1", true)}
          >
            Hello CodeSandbox
          </h1>
        </div>
    );
}

React16

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-0te4nKyx-1686967105054) (C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\ 1685930695759.png)]

React17

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-39vZwaap-1686967105055) (C:\Users\lenovo\AppData\Roaming\Typora\typora-user-images\ 1685930673755.png)]

总结

  • 16The version executes the original event first, and documentexecutes the synthetic event uniformly when the bubble arrives.
  • 17The version executes the synthetic event capture phase before the native event is executed, and executes the synthetic event in the bubbling phase after the native event is executed, and manages all events through the root node

52. jsx converts real dom process

  • Use React.createElement() or JSX to write React components, in fact all JSX will be converted to React.createElement(), Babel completes the conversion process
  • The createElement function processes special props such as key and ref to generate vDom
  • ReactDOM.render renders the generated dom to the container, and converts it into real dom for processing

53. What is JSX?

JSX stands for JavaScript XML. An XML-like syntax for building tags inside React components. JSX is a set developed for react.js 语法糖, which is also the basis for using react.js. React can work without using JSX, however using JSX can improve the readability of components, so JSX is recommended.

advantage:

  • Allows the use of familiar syntax to define HTML element trees;
  • Provide more semantic and mobile tags;
  • Program structure is easier to visualize;
  • Abstract the creation process of React Element;
  • Have control over HTML tags and the code that generates them at any time;
  • is native JavaScript.

8. WeChat Mini Programs

1. Please talk about the similarities and differences between WXML and standard html?

(1) WXML is a set of labeling language designed by the framework of the applet, which is used to construct the structure of the applet page, and its function is similar to that of html in web development

① are used to describe the structure of the page

② Both are composed of labels, attributes, etc.

③ The label names are different, and there are fewer applet labels and more single labels

④ The applet has more attributes like wx:if and expressions like { {}}

⑤ WXML can only be previewed in the WeChat applet developer tool, while HTML can be previewed in the browser

⑥ Component packaging is different, WXML repackages components

⑦ The applet runs in JS Core, there is no DOM tree and window object, and the window object and document object cannot be used in the applet

2. Please talk about the similarities and differences between WXSS and CSS?

(1) The rpx size unit is added, and the pixel unit conversion needs to be manually performed in css, such as rem

(2) WXSS supports the new size rpx, and the applet will automatically convert it on screens of different sizes

(3) Global styles and local styles are provided. The app.wxss in the root directory of the project will act on all applet pages, and the .wxss style of the local pages will only take effect on the current page

(4) WXSS only supports some css selectors:

① class selector, id selector

② Element selector

③ Union selector, descendant selector

④ Pseudo-class selectors such as ::after and ::before

3. Please talk about the role of the main directory and files of the WeChat Mini Program

(1) project.config.json: project configuration file, the most used is to configure whether to enable https verification;

(2) App.js: Set some global basic data, etc., script files of the page, store the data of the page, event processing functions, etc.;

(3) App.json: the configuration file of the current page, the appearance and performance of the configuration window, etc., the configuration items in the page will overwrite app.json;

(4) App.wxss: public style, import iconfont, etc.;

(5) pages: It contains specific pages one by one;

(6) index.json: (Configure the current page title and import components, etc.);

(7) index.wxml: the template structure file of the page;

(8) .wxss file: the style sheet file of the current page;

(9) index.js: (page logic, request and data processing, etc.)

4. Please talk about the similarities and differences between the two-way binding of the applet and vue

(1) Mini program two-way binding: first bind the input event of the text box through bindinput

① Declare a variable content in data, and dynamically bind it to the value of the text box

② In the bindinput event, the latest value in the text box can be obtained through the event parameter e.detail.value

③ Assign the latest value of the text box to the dynamically bound value content through this.setData to realize two-way binding of data

(2) Vue two-way binding: first bind @input to the text box to listen to the input event of the text box

① Dynamically bind the value attribute to the text box, whose value is the variable defined in data

② In the event bound by @input, the latest value in the input box can be obtained through the event parameter event.target.value

③ Assign the retrieved value to the variable dynamically bound to the value

(3) In general, the difference is not big, the binding events are different, and the specific ways to obtain the value are different, and to set the data in data in the applet, you need to
call the this.setData method to set

5. Briefly describe the relevant file types of the WeChat Mini Program

(1) WXML (weixin Markup Language) is a set of markup language designed by the framework, combined with basic components and event system, it can build the structure of the page. The content is mainly a set of components defined by WeChat itself.

(2) WXSS (WeiXin Style Sheets) is a style language mainly used to describe WXML component styles.

(3) JS logic processing, network request

(4) json applet settings, static configuration

(5) app.json must have this file. This file is used to configure the WeChat applet globally, determine the path of the page file, window performance, set the network timeout time, and set at least two tabBars

6. What are the value-passing (transfer data) methods of the WeChat applet?

(1) Use global variables to pass data

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-pu3nDBnO-1686967105056)(file:///C:\Users\lenovo\AppData\Local\Temp\ksohtml14876 \wps1.jpg)]

(2) Use local storage data transfer

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-H6cLbqBk-1686967105057)(file:///C:\Users\lenovo\AppData\Local\Temp\ksohtml14876 \wps2.jpg)]

(3) Use routing to pass data

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-p4zSUW0R-1686967105058)(file:///C:\Users\lenovo\AppData\Local\Temp\ksohtml14876 \wps3.jpg)]

7. What is the difference between Bindtap and catchtap?

(1) Both Bindtap and catchtap belong to the click event function, which binds the event to the component, and the function can be triggered after the component is clicked

bindtap : After the child element uses bindtap to bind the event, it will bubble to the parent element when it is executed (trigger the bingtap event bound on the parent element)

catchtap : will not bubble to the parent element, preventing the event from bubbling

8. What is the difference between wx.navigateTo(), wx.redirectTo(), wx.switchTab(), wx.navigateBack(), wx.reLaunch()?

(1) wx.navigateTo(Object): Keep the current page and jump to a page in the application. But can not jump to the tabbar page. Use wx.navigateBack to return to the original page. The page stack in the applet can have up to ten layers

(2) Wx.navigateBack(): Close the current page and return to the previous page or multi-level pages. The current page stack can be obtained through getCurrentPages to determine how many layers need to be returned

(3) wx.redirectTo(): ​​Close the current page and jump to a page in the application. But jumping to the tabbar page is not allowed

(4) wx.switchTab(): Jump to the tabBar page and close all other non-tabBar pages

(5) wx.reLaunch(): Close all pages and open to a page in the application

9. What is the difference between WeChat Mini Program and h5?

(1) 从开发的角度:H5和小程序的开发工具就非常不同,小程序都是依赖于微信客户端的,所以相对来说开发工具没有H5那么多;与标准的H5语言是不一样的;而且还独立了很多的原生app的组件,所以它在组件封装上与H5也都是有所不同

(2) 从运行环境:网页开发者需要面对的环境是各式各样的浏览器,PC 端需要面对 IE、Chrome、QQ浏览器等,在移动端需要面对Safari、Chrome以及 iOS、Android 系统中的各式 WebView 。而小程序开发过程中需要面对的是两大操作系统 iOS 和 Android 的微信客户端,以及用于辅助开发的小程序开发者工具,小程序中三大运行环境也是有所区别的。

(3) 服务器配置:因为小程序的性能会比H5 高一些,所以服务器的配置要求上来说,小程序的要求要比H5更高一些系统权限:因为微信能获取到更多的系统权限,如网络通信状态、数据缓存能力等,这些系统级权限都能与微信小程序无缝衔接,这也就是官方宣称的微信小程序能够拥有Native App(原生APP)的流畅性能。而H5 web应用对系统本身的权限的获取则相对少了很多,这一点恰巧是H5 web应用经常被诟病的地方。也因此,H5的大多数应用被圈定在业务逻辑简单、功能单一的范围上。

(4) 标签名字:写 HTML 的时候,经常会用到的标签是 div, p, span,小程序的 WXML 用的标签是 view, button, text 等等,这些标签就是小程序给开发者包装好的基本能力。小程序多了一些 wx:if 这样的属性以及 { { }} 这样的表达式在网页的一般开发流程中,我们通常会通过 JS 操作 DOM (对应 HTML 的描述产生的树),以引起界面的一些变化响应用户的行为。

10.小程序和vue写法区别?

(1) 事件定义区别:vue通过@绑定事件,小程序通过bind

(2) 事件函数传值:vue传值直接写在函数括号中,微信小程序传值需要用data-自定义名字={ {需要传递的值}}

(3) 关键字引用:vue中属性名前面加 “:” 或者 v-bind,微信小程序中只需要属性值加“{ {}}”包起来就行

(4) 指令使用方式:vue中通过v-使用,小程序中通过wx:使用

11.Rpx的理解:

(1) Rpx是微信小程序中响应单位

(2) rpx是微信小程序独有的、解决屏幕自适应的尺寸单位

(3) 可以根据屏幕宽度进行自适应,不论大小屏幕,规定屏幕宽为750rpx,再页面宽度750px时,1rpx = 1px

12.微信小程序可以做dom操作吗?

(1) 微信小程序不支持document.querySelect获取元素,因为微信小程序的渲染层和逻辑层是独立的,但是它内置了获取元素的两种方法

① wx.createSelectorQuery()获取dom元素

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-oEW3uzli-1686967105059)(file:///C:\Users\lenovo\AppData\Local\Temp\ksohtml14876\wps4.jpg)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XH7ohB3C-1686967105059)(file:///C:\Users\lenovo\AppData\Local\Temp\ksohtml14876\wps5.jpg)]

13.小程序和vue区别?

(1) 生命周期不一样,微信小程序生命周期比较简单

(2) The data binding is also different. Wechat applet data binding needs to use { {}}, vue directly: just fine

(3) Display and hide elements. In vue, use v-if and v-show to control the display and hiding of elements. In applets, use wx-if and hidden to control the display and hiding of elements

(4) Event processing is different. In small programs, use bindtap(bind+event) or catchtap(catch+event) to bind events, vue: use v-on:event to bind events, or use @event to bind events

(5) The two-way binding of data is also different. In vue, you only need to add v-model to the form element, and then bind a corresponding value in data. When the content of the form element changes, the corresponding value in data The value of will also change accordingly, which is a very nice point of vue. The WeChat applet must obtain the form element, change the value, and then assign the value to a variable declared in data.

14. Mini-program custom tabbar understanding?

(1) First of all, I am being criticized. Configure tabbar in App.json, enable custom custom tabbar, and create a custom-tab-bar file after configuration. At this time, the file content will be generated at the bottom of the applet. Add the structure code of tabBar to index.wxml, and add it to index.js Data Configuration and Event Methods

15. How to set the cache for the WeChat applet?

(1) wx.getStorage/wx.getStorageSync reads the local cache, and writes data to the cache through wx.setStorage/wx.setStorageSync, where the interface with the Sync suffix indicates a synchronous interface

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-BOmNe545-1686967105060)(file:///C:\Users\lenovo\AppData\Local\Temp\ksohtml14876 \wps6.jpg)]

16. How does the WeChat Mini Program make network requests?

(1) wx.request(Object object) is used to send network requests

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-r5VZUL7r-1686967105062)(file:///C:\Users\lenovo\AppData\Local\Temp\ksohtml14876 \wps7.jpg)]

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-so2LhJfi-1686967105063)(file:///C:\Users\lenovo\AppData\Local\Temp\ksohtml14876 \wps8.jpg)]

17. Mini Program life cycle is divided into three parts

(1) Application level:

① onLaunch: Triggered when the mini-program is initialized, only triggered once globally

② onShow: Triggered when the applet starts or switches to the foreground display

③ onHide: Triggered when the applet enters the background from the foreground (such as switching to other App

④ onError: Triggered when a script error occurs in the applet or an error is reported in an API call

(2) Page level:

① onLoad: Executed when the page is loaded, only once

② onShow: Executed when the page is displayed, executed multiple times

③ onReady: Executed when the page is rendered for the first time, only once

④ onHide: Executed when the page enters the background from the foreground

⑤ onUnload: executed when the page is unloaded

(3) Component level:

created (important): triggered when the component instance has just been created

attached (important): triggered after the component is fully initialized and enters the page node tree

③ ready: Executed after the layout of the component in the view layer is completed

④ moved: Executed when the component instance is moved to another location in the node tree

detached (important): triggered after the component leaves the page node tree

⑥ Error: Executed whenever a component method throws an error

18. 微信小程序如何做模块化?

(1) 可以将一些公共的代码抽离成为一个单独的 js 文件,作为一个模块。模块只有通过 module.exports 或者 exports 才能对外暴露接口

(2) 需要使用这些模块的文件中,使用 require 将公共代码引入

19. 微信所有api都放在哪里,简单介绍几个

(1) 小程序全局对象是: wx,所有的 API 都保存在 wx 对象中

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IzoRS18A-1686967105064)(file:///C:\Users\lenovo\AppData\Local\Temp\ksohtml14876\wps9.jpg)]

20. 微信小程序应用和页面生命周期触发顺序?

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZlYZbvim-1686967105064)(file:///C:\Users\lenovo\AppData\Local\Temp\ksohtml14876\wps10.jpg)]

21. 微信小程序自定义组件使用

(1) 创建components文件夹

(2) 创建组件文件(例tabs),新建为component形式

(3) 在tabs的json文件中设置component:true

(4) 在需要引入的组件页面的json文件中,在usingComponent里面写键值对,组件名:路径

(5) 在需要页面写入标签

注意:WXML 节点标签名只能是小写字母、中划线和下划线的组合

22. 微信小程序事件通道使用

The WeChat Mini Program event channel (event bus) is a mechanism for communicating between multiple pages or components of a Mini Program by triggering events. When jumping to the target page or component through the wx.navigateTo or wx.redirectTo method, pass in the events parameter and assign it to the event channel object

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-Z9pQwqTy-1686967105065)(file:///C:\Users\lenovo\AppData\Local\Temp\ksohtml14876 \wps11.jpg)]

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-6a1HlQJq-1686967105066)(file:///C:\Users\lenovo\AppData\Local\Temp\ksohtml14876 \wps12.jpg)]

23. How to use the vant component library for applets

If the small program is created with js as the web page scripting language, and there is no package.json file, the npm command cannot be used

First initialize npm through npm init to generate a package.json file

Download the component library through vantweapp official website npm

Build npm through tools in the WeChat applet

Remove "style": "v2" in app.json to avoid style confusion caused by the style of the applet being higher than vant

Register components using Components in app.json

24. Parent-child transfer of WeChat applets

父传子: Bind attributes through parent component tags, and child components receive attributes in properties

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-olTg2Lfx-1686967105067)(file:///C:\Users\lenovo\AppData\Local\Temp\ksohtml14876 \wps13.jpg)]

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-NMW1E5Xq-1686967105068)(file:///C:\Users\lenovo\AppData\Local\Temp\ksohtml14876 \wps14.jpg)]

子传父: Through the parent component bind custom event, bind its own function, and the child component passes this.triggerEvent('parent component bind event name', passing parameters) to the parent component binding function in the trigger function

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-oNSSzdfi-1686967105068)(file:///C:\Users\lenovo\AppData\Local\Temp\ksohtml14876 \wps15.jpg)]

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-JOYkl8El-1686967105069)(file:///C:\Users\lenovo\AppData\Local\Temp\ksohtml14876 \wps16.jpg)]

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-s8Gidbyv-1686967105070)(file:///C:\Users\lenovo\AppData\Local\Temp\ksohtml14876 \wps17.jpg)]

25. Mini Program authorization login

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-J7YYIVIy-1686967105071)(file:///C:\Users\lenovo\AppData\Local\Temp\ksohtml14876 \wps18.jpg)]

26. web-view

web-view is a web browser component that can be used to host a web page container, and it will automatically fill the entire page.

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vj1a9jN1-1686967105072)(file:///C:\Users\lenovo\AppData\Local\Temp\ksohtml14876\wps19.jpg)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mQueHEZG-1686967105073)(file:///C:\Users\lenovo\AppData\Local\Temp\ksohtml14876\wps20.jpg)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1MvzbHfJ-1686967105074)(file:///C:\Users\lenovo\AppData\Local\Temp\ksohtml14876\wps21.jpg)]

六、Webpack 篇

1.webpack五大核心

  1. Entry - 入口

Entry 指示 Webpack 从哪个模块开始构建内部依赖图,以及如何将所有依赖项连接在一起。

  1. Output - 输出

Output 定义了 Webpack 构建的输出文件的位置和文件名。

  1. Loader - 加载器

Loader 用于对模块的源代码进行转换,以便于 Webpack 处理。例如,当 Webpack 遇到一个 “.css” 文件时,使用 “css-loader” 和 “style-loader” 将其转换为 JavaScript 代码以便于在浏览器中呈现样式。

  1. Plugin - 插件

Plugin 在 Webpack 的构建过程中扮演一个关键的角色,它可以完成各种各样的任务,例如压缩代码、拷贝文件到输出目录、创建全局变量等等。

  1. Mode - 模式

Mode 是 Webpack 4 引入的一个新特性,它提供了三种不同的构建模式,即 “development”、“production” 和 “none”,分别对应着开发模式、生产模式和不设置模式。

1. Talk about your understanding of Webpack (what is Webpack?)

Webpack is a static module packager that can analyze the dependencies of each module. All resources in the project are modules. By analyzing the dependencies between modules, a dependency graph is built recursively inside it, which contains the required components of the application. each module, and then package those modules into one or more bundle. The final compiled output modules are HTML, JavaScript, CSS and various static files (pictures, fonts, etc.).

Webpack is like a production line, it needs to go through a series of processing processes (loader) before converting source files into output results. The responsibility of each processing process on this production line is single, and there are dependencies among multiple processes. Only after the current processing is completed can it be handed over to the next process for processing.
A plug-in is like a function inserted into the production line to process the resources on the production line at a specific time. Webpack will broadcast events during operation, and the plug-in only needs to listen to the events it cares about, and can join the production line to change the operation of the production line.

The main functions of webpack are as follows:

  • Module packaging can package and integrate the files of different modules together, and ensure that the references between them are correct and the execution is orderly. By using packaging, we can freely divide file modules according to our own business during development to ensure the clarity and readability of the project structure.
  • Compilation and compatibility in the "ancient era" of the front end, handwriting a bunch of browser compatible code has always been a headache for front-end engineers, but today this problem has been greatly weakened, through the Loader mechanism of webpack, not only can help us By polyfilling the code, you can also compile and convert files in formats that cannot be recognized by browsers, such as .less, .vue, and .jsx, so that we can use new features and new syntax for development during development and improve development efficiency.
  • Capability expansion Through the Plugin mechanism of webpack, we can further realize a series of functions such as on-demand loading and code compression on the basis of modular packaging and compiling compatibility, helping us to further improve automation, engineering efficiency and packaging output quality .

2. What is the packaging process/packaging principle/build process of Webpack?

  1. Initialization: start the build, read and merge configuration parameters, load plugin, instantiate Compiler
  2. Compilation: Starting from the Entry, serially call the corresponding Loader for each Module to translate the content in the file, and then find the Module that the Module depends on, and compile it recursively
  3. Output: Combine the compiled Module into Chunk, convert the Chunk into a file, and output it to the file system

detail:

Webpack CLI parses CLI parameters through the yargs module and converts them into configuration object options (single entry: Object, multi-entry: Array), and calls webpack(option) to create a compiler object.

If there is an option.plugin, then traverse and call plugin.apply() to register the plugin,

Determine whether watch is enabled, if enabled, call compiler.watch, otherwise call compiler.run, and start building.

Create a Compilation object to collect all resources and information, and then trigger the make hook.

The make phase recurses all dependencies from the entry point,

Call the corresponding Loader to translate the content in the file each time it traverses, then generate AST, traverse the AST to find the next dependency and continue recursively.

Assemble the chunk according to the relationship between the entry and the module, and output it to a file in dist.

In the above process, webpack will broadcast a specific event at a specific point in time (using the tapable module ), the plug-in listens to the event and executes the corresponding logic, and the plug-in can call the api provided by webpack to change the running result of webpack

3. The role of the loader

The loader in webpack is a function , mainly to realize the conversion of the source code , so the loader function will take the source code as a parameter , for example, convert ES6 to ES5, convert less to css, and then convert css to js, ​​so that it can be embedded in html file .

By default, webpack only supports packaging js and json files, but for other types of files such as css, html, png, etc., webpack is helpless. Therefore, it is necessary to configure the corresponding loader to parse and convert the file content.

4. What are the common Loaders? What problem do they solve?

Commonly used loaders are as follows:

  • image-loader: Load and compress image files.
  • less-loader: loads and compiles LESS files.
  • sass-loader: Load and compile SASS/SCSS files.
  • css-loader: load CSS, support modularization, compression, file import and other features, use css-loader must use style-loader.
  • style-loader: It is used to mount the compiled CSS style to the style tag of the page. Pay attention to the execution order of loaders, style-loader should be placed first, and loaders are executed from back to front.
  • babel-loader: Convert ES6 to ES5
  • postcss-loader: Extend CSS syntax, use the next-generation CSS, and can automatically complete CSS3 prefixes with the autoprefixer plug-in.
  • eslint-loader: Lint JavaScript code via ESLint.
  • vue-loader: Load and compile Vue components.
  • file-loader: output the file to a folder, and refer to the output file through the relative URL in the code (processing pictures and fonts)
  • url-loader:与 file-loader 类似,区别是用户可以设置一个阈值,大于阈值会交给 file-loader 处理,小于阈值时返回文件 base64 形式编码 (处理图片和字体)。
  • source-map-loader:加载额外的 Source Map 文件,以方便断点调试。

5. plugin的作用

plugin是一个类,类中有一个apply()方法,主要用于Plugin的安装,可以在其中监听一些来自编译器发出的事件,在合适的时机做一些事情。

webpack中的plugin赋予其各种灵活的功能,例如打包优化、资源管理、环境变量注入等,它们会运行在webpack的不同阶段(钩子 / 生命周期),贯穿了webpack整个编译周期。目的在于「解决 loader 无法实现的其他事」。

6. 有哪些常见的Plugin?他们是解决什么问题的?

  • html-webpack-plugin:可以复制一个有结构的html文件,并自动引入打包输出的所有资源(JS/CSS)
  • clean-webpack-plugin:重新打包自动清空 dist 目录
  • mini-css-extract-plugin:提取 js 中的 css 成单独文件
  • optimize-css-assets-webpack-plugin:压缩css
  • uglifyjs-webpack-plugin:压缩js
  • commons-chunk-plugin:提取公共代码
  • define-plugin:定义环境变量

7. Webpack中Loader和Plugin的区别

运行时机
1.loader运行在编译阶段
2.plugins 在整个周期都起作用

使用方式
Loader:1.下载 2.使用
Plugin:1.下载 2.引用 3.使用

loader is a file loader, which can load resource files, and perform some processing on these files, such as compiling, compressing, etc., and finally pack them together into the specified file; plugin endows webpack with various flexible functions, such as packaging optimization, resource management , environment variable injection, etc., the purpose is to solve other things that the loader cannot achieve.

At runtime, the loader runs before packaging files; the plugin works throughout the compilation cycle.

In terms of configuration, the loader is configured in module.rules, as the parsing rules of the module, and the type is an array. Each item is an Object, which contains test (type file), loader, options (parameters) and other attributes; plugin is configured separately in plugins, the type is an array, each item is an instance of plugin, and parameters are constructed function passed in.

8. How does the hot update of webpack work? Explain its principle?

The core of the hot update is that the client pulls the updated file from the server. To be precise, it is chunk diff (the part of the chunk that needs to be updated). In fact, a websocket is maintained between the webpack-dev-server and the browser. When the local When the resource changes, webpack-dev-server will push an update to the browser, and bring the hash when it was built, so that the client can compare it with the last resource. After the client compares the differences, it will initiate an Ajax request to the webpack-dev-server to obtain the changed content (file list, hash), so that the client can use this information to continue to initiate a jsonp request to the webpack-dev-server to obtain the chunk. Incremental update.

The subsequent part (how to deal with the incremental update? Which states should be kept? Which ones need to be updated?) is done by HotModulePlugin, which provides relevant APIs for developers to process according to their own scenarios, such as react-hot-loader and vue-loader uses these APIs to implement hot updates.

详细:
1、在 webpack 的 watch 模式下,文件系统中某一个文件发生修改,webpack 监听到文件变化,根据配置文件对模块重新编译打包,并将打包后的代码通过简单的 JavaScript 对象保存在内存中。
2、webpack-dev-server 和 webpack 之间的接口交互,而在这一步,主要是 dev-server 的中间件webpack-dev-middleware 和 webpack 之间的交互,webpack-dev-middleware 调用 webpack 暴露的 API对代码变化进行监控,并且告诉 webpack,将代码打包到内存中。
3、webpack-dev-server 对文件变化的一个监控,这一步不同于第一步,并不是监控代码变化重新打包。当我们在配置文件中配置了devServer.watchContentBase 为 true 的时候,Server 会监听这些配置文件夹中静态文件的变化,变化后会通知浏览器端对应用进行 live reload。注意,这儿是浏览器刷新,和 HMR 是两个概念
4、webpack-dev-server 代码的工作,该步骤主要是通过 sockjs(webpack-dev-server 的依赖)在浏览器端和服务端之间建立一个 websocket 长连接,将 webpack 编译打包的各个阶段的状态信息告知浏览器端,
同时也包括第三步中 Server 监听静态文件变化的信息。浏览器端根据这些 socket 消息进行不同的操作。当然服务端传递的最主要信息还是新模块的 hash 值,后面的步骤根据这一 hash 值来进行模块热替换。
webpack-dev-server/client 端并不能够请求更新的代码,也不会执行热更模块操作,而把这些工作又交回给了 webpack,webpack/hot/dev-server 的工作就是根据 webpack-dev-server/client 传给它的信息以及 dev-server 的配置决定是刷新浏览器呢还是进行模块热更新。当然如果仅仅是刷新浏览器,也就没有后面那些步骤了。HotModuleReplacement.runtime 是客户端 HMR 的中枢,它接收到上一步传递给他的新模块的 hash 值,它通过 JsonpMainTemplate.runtime 向 server 端发送 Ajax 请求,服务端返回一个 json,该 json 包含了所有要更新的模块的 hash 值,获取到更新列表后,该模块再次通过 jsonp 请求,获取到最新的模块代码。
5、决定 HMR 成功与否的关键步骤,在该步骤中,HotModulePlugin 将会对新旧模块进行对比,决定是否更新模块,在决定更新模块后,检查模块之间的依赖关系,更新模块的同时更新模块间的依赖引用。最后一步,当 HMR 失败后,回退到 live reload 操作,也就是进行浏览器刷新来获取最新打包代码。

9. 如何解决循环依赖问题

Webpack 中将 require 替换为 *webpack_require*,会根据 moduleId 到 installedModules 找是否加载过,加载过则直接返回之前的 export,不会重复加载。

10. 如何提高Webpack构建速度

1. 代码压缩

  • JS compression
    webpack 4.0 supports code compression by default in the production environment, that is, in mode=production mode. In fact, webpack 4.0 uses the compression plugin terser-webpack-plugin by default. Before that, uglifyjs-webpack-plugin was used. The difference between the two is that the latter does not compress ES6 very well. At the same time, we can open the parallel parameter and use Multi-process compression for faster compression.
  • CSS minification
    CSS minification is usually to remove useless whitespace etc., because it is difficult to modify selectors, property names, values, etc. Another plugin can be used: css-minimizer-webpack-plugin.
  • HTML compression
    When using the HtmlWebpackPlugin plug-in to generate HTML templates, optimize the html by configuring the attribute minify.
module.exports = {
plugin:[
  new HtmlwebpackPlugin({
    minify:{
      minifyCSS: false, // 是否压缩css
      collapseWhitespace: false, // 是否折叠空格
      removeComments: true // 是否移除注释
    }
  })
  ]
}

2. Image compression

configurationimage-webpack-loader

3. Tree Shaking

Tree Shaking is a term that means eliminating dead code in computers, relying on ES Module's static syntax analysis (without executing any code, you can clearly know the dependencies of modules). There are two options for implementing Tree shaking in webpack:

usedExports: by marking whether certain functions are used, and then optimized through Terser

module.exports = {
    ...
    optimization:{
        usedExports
    }
  }

After use, the unused code will be added unused harmony export mul comment in the webpack package to inform Terser that this code can be deleted during optimization.

sideEffects: Skip the entire module/file and directly check whether the file has side effects

sideEffects is used to tell webpack compiler which modules have side effects. The configuration method is to set the sideEffects property in package.json. If sideEffects is set to false, it tells webpack that it can safely delete unused exports. If some files need to be kept, they can be set in the form of an array, such as:

"sideEffecis":[
    "./src/util/format.js",
    "*.css" // 所有的css文件
]

4. Shrink the packaging domain

Exclude modules that webpack does not need to parse, that is, use as few modules as possible when using the loader. With the help of the two parameters include and exclude, it is specified that the loader is only applied to those modules and which modules are not applied.

5. Reduce redundant code from ES6 to ES5

use 、bable-plugin-transform-runtimeplugin

6. Extract public code

By configuring the CommonsChunkPlugin plug-in, the common code of multiple pages is extracted into a separate file

7. Other

Lazy loading of components, lazy loading of routes, enabling gzip, cdn on public third-party packages, configuring cache to cache Loader’s compiled copy of files, configuring resolve to improve file search speed (@: src)


7. Performance Optimization

1. Browser cache optimization

In order to 浏览器缓存get the most out of it, the strategy should try to follow the following five points to get 浏览器缓存the most out of it.

  • "Consider rejecting all caching policies" :Cache-Control:no-store
  • "Consider whether the resource is requested to the server every time" :Cache-Control:no-cache
  • "Consider whether the resource is cached by the proxy server" :Cache-Control:public/private
  • "Consider resource expiration time" :Expires:t/Cache-Control:max-age=t,s-maxage=t
  • "Consider negotiation caching" :Last-Modified/Etag

缓存策略Realized by setting the message, it is divided into **"strong cache/mandatory cache" andHTTP "negotiation cache/comparison cache"** in form . For the convenience of comparison, the author uses legends to show some details, I believe you have a better understanding. The whole mechanism is straightforward, . If it hits , use it directly ; if it doesn't hit , send a request to the server to check whether it hits ; if it hits , the server returns 304 to notify the browser to use , otherwise returns .
insert image description here
insert image description here
缓存策略先走强缓存,若命中失败才走协商缓存强缓存强缓存强缓存协商缓存协商缓存本地缓存最新资源

有两种较常用的应用场景值得使用缓存策略一试,当然更多应用场景都可根据项目需求制定。

  • 「频繁变动资源」:设置Cache-Control:no-cache,使浏览器每次都发送请求到服务器,配合Last-Modified/ETag验证资源是否有效
  • 「不常变化资源」:设置Cache-Control:max-age=31536000,对文件名哈希处理,当代码修改后生成新的文件名,当HTML文件引入文件名发生改变才会下载最新文件

2. 渲染层面性能优化

**「渲染层面」**的性能优化,无疑是如何让代码解析更好执行更快。因此笔者从以下五方面做出建议。

  • 「CSS策略」:基于CSS规则
  • 「DOM策略」:基于DOM操作
  • 「阻塞策略」:基于脚本加载
  • 「回流重绘策略」:基于回流重绘
  • 「异步更新策略」:基于异步更新

上述五方面都是编写代码时完成,充满在整个项目流程的开发阶段里。因此在开发阶段需时刻注意以下涉及到的每一点,养成良好的开发习惯,性能优化也自然而然被使用上了。

渲染层面性能优化更多表现在编码细节上,而并非实体代码。简单来说就是遵循某些编码规则,才能将渲染层面性能优化发挥到最大作用。

**「回流重绘策略」**在渲染层面性能优化里占比较重,也是最常规的性能优化之一。上年笔者发布的掘金小册《玩转CSS的艺术之美》使用一整章讲解回流重绘,本章已开通试读,更多细节请戳这里。

CSS策略

  • 避免出现超过三层的嵌套规则
  • 避免为ID选择器添加多余选择器
  • Avoid using 标签选择器instead类选择器
  • Avoid using 通配选择器, declare rules only for target nodes
  • To avoid repeated matching of repeated definitions, focus on可继承属性

DOM strategy

  • cacheDOM计算属性
  • avoid too muchDOM操作
  • DOMFragmentBatching with cachingDOM操作

blocking strategy

  • The script has DOM/其它脚本a strong dependency on: ``settingsdefer
  • The script DOM/其它脚本does not have a strong dependency on: ``settingsasync

reflow redraw strategy

  • cacheDOM计算属性
  • Use class to merge styles to avoid changing styles item by item
  • Using displaythe controls DOM显隐, set theDOM离线化

Asynchronous Update Policy

  • Wrap it when 异步任务modified inDOM微任务

3. Six indicators for performance optimization

六大指标It basically includes most of 性能优化the details and can be used as 九大策略a supplement. 性能优化建议According to the characteristics of each article, the author 指标divides it into the following six aspects.

  • "Loading optimization" : performance optimization that can be done when resources are loaded
  • "Execution optimization" : The performance optimization that resources can do during execution
  • "Rendering optimization" : performance optimization that can be done when resources are rendered
  • "Style optimization" : performance optimization that styles can do when coding
  • "Script optimization" : performance optimization that scripts can do when coding
  • "V8 engine optimization" : V8引擎performance optimization for features

Eight, other miscellaneous articles

1. What are the common browser kernels?

  • It is mainly divided into two parts: the rendering engine (layout engineer or Rendering Engine) and the JS engine.
    • Rendering engine: Responsible for obtaining the content of the web page (HTML, XML, images, etc.), organizing information (such as adding CSS, etc.), and calculating the display method of the web page, and then outputting it to the monitor or printer. Different browser kernels have different syntax interpretations for web pages, so the rendering effects are also different. All web browsers, email clients, and other applications that edit and display web content require a kernel.
    • The JS engine: parses and executes javascript to realize the dynamic effect of the webpage.
  • At first, the rendering engine and the JS engine were not clearly distinguished. Later, the JS engine became more and more independent, and the kernel tended to only refer to the rendering engine.
  • common kernel
    • Trident kernel: IE, MaxThon, TT, The World, 360, Sogou browser, etc. [aka MSHTML]
    • Gecko kernel: Netscape6 and above, FF, MozillaSuite / SeaMonkey, etc.
    • Presto kernel: Opera7 and above. [Opera kernel was originally: Presto, now: Blink;]
    • Webkit kernel: Safari, Chrome, etc. [Chrome: Blink (fork of WebKit)]

2. What are the ways to optimize the performance of the front-end of the webpage?

1. Compress css, js, pictures
2. Reduce the number of http requests, merge css, js, merge pictures (Sprite image)
3. Use CDN
4. Reduce the number of dom elements
5. Lazy loading of pictures
6. Static resources also use cookieless Domain name
7. Reduce dom access (caching dom)
8. Use event delegation skillfully
9. Set style sheet to the top and script to the bottom

3. What process does the webpage go through from inputting URL to rendering?

It can be roughly divided into the following 7 steps:

  • Enter URL;
  • Send it to the DNS server, and obtain the ip address corresponding to the web server corresponding to the domain name;
  • Establish a TCP connection with the web server;
  • The browser sends an http request to the web server;
  • The web server responds to the request and returns the data of the specified url (or an error message, or a redirected new url address);
  • The browser downloads the data returned by the web server and parses the html source file;
  • Generate a DOM tree, parse css and js, render the page until the display is complete;

4. What is the difference between a thread and a process?

  • A program has at least one process, and a process has at least one thread.
  • The division scale of threads is smaller than that of processes, so that the concurrency of multi-threaded programs is high.
  • In addition, a process has an independent memory unit during execution, and multiple threads share the memory, which greatly improves the operating efficiency of the program.
  • There is still a difference between a thread and a process during execution. Each independent thread has an entry point for program execution, a sequential execution sequence, and an exit point for the program. However, threads cannot be executed independently, and must depend on the application program, and the application program provides multiple thread execution control.
  • From a logical point of view, the meaning of multithreading is that in an application, multiple execution parts can be executed at the same time. However, the operating system does not regard multiple threads as multiple independent applications to implement process scheduling and management and resource allocation. This is the important difference between process and thread.

5. What are the common status codes of HTTP?

100 Continue 继续,一般在发送post请求时,已发送了http header之后服务端将返回此信息,表示确认,之后发送具体参数信息
200 OK 正常返回信息
201 Created 请求成功并且服务器创建了新的资源
202 Accepted 服务器已接受请求,但尚未处理
301 Moved Permanently 请求的网页已永久移动到新位置。
302 Found 临时性重定向。
303 See Other 临时性重定向,且总是使用 GET 请求新的 URI。
304 Not Modified 自从上次请求后,请求的网页未修改过。
400 Bad Request 服务器无法理解请求的格式,客户端不应当尝试再次使用相同的内容发起请求。
401 Unauthorized 请求未授权。
403 Forbidden 禁止访问。
404 Not Found 找不到如何与 URI 相匹配的资源。
500 Internal Server Error 最常见的服务器端错误。
503 Service Unavailable 服务器端暂时无法处理请求(可能是过载或维护)。

6. 图片懒加载?

当页面滚动的时间被触发 -> 执行加载图片操作 -> 判断图片是否在可视区域内 -> 在,则动态将data-src的值赋予该图片

7. 移动端性能优化?

  • 尽量使用css3动画,开启硬件加速
  • 适当使用touch时间代替click时间
  • 避免使用css3渐变阴影效果
  • 可以用transform: translateZ(0) 来开启硬件加速
  • 不滥用float。float在渲染时计算量比较大,尽量减少使用
  • Do not abuse web fonts. Web fonts need to be downloaded, parsed, and repainted on the current page
  • Reasonable use of requestAnimationFrame animation instead of setTimeout
  • The properties in css (css3 transitions, css3 3D transforms, opacity, webGL, video) will trigger GUP rendering, which consumes power

8. Three-way handshake and four-way handshake strategy for TCP transmission

  • Three-way handshake:

    In order to accurately deliver data to the target, the TCP protocol uses a three-way handshake strategy. After using the TCP protocol to send the data packet, TCP will not ignore the situation after the transmission, he will definitely confirm to the other party whether it has been delivered, and use the TCP flag during the handshake process: SYN and ACK

    • The sender first sends a data packet with the SYN flag to the other party
    • After the receiving end receives it, it returns a data packet with the SYN/ACK flag to show the confirmation information
    • Finally, the sender returns a data packet with an ACK flag, which means that the "handshake" is over
  • If there is a certain interruption during the handshake process, the TCP protocol will send the same data packets in the same order again


  • Disconnecting a TCP connection requires "four waves"
    • The first wave: the active closing party sends a FIN to pay attention to the data transmission from the active party to the passive closing party, that is, the active closing party warns the passive closing party: I will not send you any more data (in the FIN packet For the data sent before, if the corresponding ACK confirmation message is not received, the active closing party will still resend the data). However, at this time, the actively closed party can still accept data
    • The second wave: After the passive closing party receives the FIN packet, it sends an ACK to the other party, confirming that the serial number has received the serial number + 1 (same as SYN, one FIN occupies one serial number)
    • Third wave: The passive closing party sends a FIN. It is used to close the data transmission from the passive closing party to the active closing party, that is to tell the active closing party that my data has been sent and I will not send you data.
    • The fourth wave: After the active closing party receives the FIN, it sends an ACK to the passive closing party, confirming that the serial number is the received serial number + 1, so far, four waved hands are completed

9. HTTP and HTTPS, why is HTTPS safe?

  • The HTTP protocol is usually carried on top of the TCP protocol, and a security protocol layer (SSL or TSL) is added between HTTP and TCP. At this time, it becomes what we often call HTTPS
  • The default HTTP port number is 80, and the HTTPS port number is 443
  • Because the network request needs to be forwarded by many server routes in the middle, the intermediate nodes may tamper with the information, and if you use HTTPS, the key is only with you and the terminal station. The reason why https is safer than http is because it uses ssl/ tls protocol transmission. Including certificates, traffic forwarding, load balancing, page adaptation, browser adaptation, refer transfer, etc., ensuring the security of the transmission process

10. The difference between axios and fetch

Axios is an HTTP client based on Promise for browsers and nodejs. It is essentially an encapsulation of native XHR, but it is an implementation version of Promise, which conforms to the latest ES specification. It has the following characteristics

  • Create XMLHttpRequest from browser
  • Support Promise API
  • Client support to prevent CSRF
  • Provides some interfaces for concurrent requests (important, it facilitates a lot of operations)
  • Create http request from node.js
  • Intercept requests and responses
  • Transform request and response data
  • cancel request
  • Automatically convert JSON data

fetchAdvantages:

  • The syntax is concise and more semantic
  • Based on standard Promise implementation, support async/await
  • Isomorphism is convenient, use isomorphic-fetch
  • It is more low-level and provides rich APIs (request, response)
  • Separated from XHR, it is a new implementation in the ES specification

There is a problem with fetch

  • fetch is a low-level API, you can consider it as a native XHR, so it is not so comfortable to use and needs to be encapsulated.
  • fetch only reports errors for network requests, and treats 400 and 500 as successful requests. When the server returns 400 and 500 error codes, it will not reject. Fetch will be rejected only when the request cannot be completed due to network errors.
  • fetch does not bring cookies by default, you need to add configuration items: fetch(url, {credentials: 'include'})
  • Fetch does not support abort and does not support timeout control. The timeout control implemented by using setTimeout and Promise.reject cannot prevent the request process from continuing to run in the background, resulting in a waste of traffic
  • Fetch has no way to monitor the progress of the request natively, while XHR can

Nine, subjective questions

1. What projects have you worked on? Talk about the technology used in a certain project in detail.

注意:用心找自己做的项目中自己感觉最拿出来手的(复杂度最高,用的技术最多的项目),描述的时候尽可能往里面添加一些技术名词
布局我们用html5+css3
我们会用reset.css重置浏览器的默认样式
JS框架的话我们选用的是jQuery(也可能是Zepto)
我们用版本控制工具git来协同开发
我们会基于gulp搭建的前端自动化工程来开发(里面包含有我们的项目结构、我们需要引用的第三方库等一些信息,我们还实现了sass编译、CSS3加前缀等的自动化)
我们的项目中还用到了表单验证validate插件、图片懒加载Lazyload插件

2. 你遇到过比较难的技术问题是?你是如何解决的?

3. 常使用的库有哪些?常用的前端开发工具?开发过什么应用或组件?

4. 除了前端以外还了解什么其它技术么?你最最厉害的技能是什么?

5. 对前端开发工程师这个职位是怎么样理解的?它的前景会怎么样?

前端是最贴近用户的程序员,比后端、数据库、产品经理、运营、安全都近。
1、实现界面交互
2、提升用户体验
3、有了Node.js,前端可以实现服务端的一些事情
前端是最贴近用户的程序员,前端的能力就是能让产品从 90分进化到 100 分,甚至更好,
参与项目,快速高质量完成实现效果图,精确到1px;
与团队成员,UI设计,产品经理的沟通;
做好的页面结构,页面重构和用户体验;
处理hack,兼容、写出优美的代码格式;
针对服务器的优化、拥抱最新前端技术。

  • 「阻塞策略」:基于脚本加载
  • "Reflow redraw strategy" : redraw based on reflow
  • "Asynchronous update strategy" : based on asynchronous update

The above five aspects are all completed when writing code, and are filled in the development stage of the entire project process. Therefore, in the development stage, you should always pay attention to each point involved in the following, develop good development habits, 性能优化and it will be used naturally.

渲染层面More 性能优化performance in the coding details, rather than physical code. To put it simply, it is to follow certain coding rules in order to maximize the effect of 渲染层面.性能优化

** "Reflow redrawing strategy" ** occupies a relatively large proportion in the 渲染层面game 性能优化, and it is also one of the most conventional ones 性能优化. Last year, the author released the gold nugget booklet "Playing with the Beauty of CSS Art" with a whole chapter to explain 回流重绘. This chapter has been opened for trial reading. For more details, please click here.

css strategy

  • Avoid more than three layers of嵌套规则
  • Avoid ID选择器adding redundant selectors for
  • Avoid using 标签选择器instead类选择器
  • Avoid using 通配选择器, declare rules only for target nodes
  • To avoid repeated matching of repeated definitions, focus on可继承属性

DOM strategy

  • cacheDOM计算属性
  • avoid too muchDOM操作
  • DOMFragmentBatching with cachingDOM操作

blocking strategy

  • The script has DOM/其它脚本a strong dependency on: ``settingsdefer
  • The script DOM/其它脚本does not have a strong dependency on: ``settingsasync

reflow redraw strategy

  • cacheDOM计算属性
  • Use class to merge styles to avoid changing styles item by item
  • Using displaythe controls DOM显隐, set theDOM离线化

Asynchronous Update Policy

  • Wrap it when 异步任务modified inDOM微任务

3. Six indicators for performance optimization

六大指标It basically includes most of 性能优化the details and can be used as 九大策略a supplement. 性能优化建议According to the characteristics of each article, the author 指标divides it into the following six aspects.

  • 「加载优化」:资源在加载时可做的性能优化
  • 「执行优化」:资源在执行时可做的性能优化
  • 「渲染优化」:资源在渲染时可做的性能优化
  • 「样式优化」:样式在编码时可做的性能优化
  • 「脚本优化」:脚本在编码时可做的性能优化
  • 「V8引擎优化」:针对V8引擎特征可做的性能优化

八、其他杂项篇

1. 常见的浏览器内核有哪些?

  • 主要分成两部分:渲染引擎(layout engineer或Rendering Engine)和JS引擎。
    • 渲染引擎:负责取得网页的内容(HTML、XML、图像等等)、整理讯息(例如加入CSS等),以及计算网页的显示方式,然后会输出至显示器或打印机。浏览器的内核的不同对于网页的语法解释会有不同,所以渲染的效果也不相同。所有网页浏览器、电子邮件客户端以及其它需要编辑、显示网络内容的应用程序都需要内核。
    • JS引擎则:解析和执行javascript来实现网页的动态效果。
  • 最开始渲染引擎和JS引擎并没有区分的很明确,后来JS引擎越来越独立,内核就倾向于只指渲染引擎。
  • 常见内核
    • Trident 内核:IE, MaxThon, TT, The World, 360, 搜狗浏览器等。[又称 MSHTML]
    • Gecko 内核:Netscape6 及以上版本,FF, MozillaSuite / SeaMonkey 等
    • Presto 内核:Opera7 及以上。 [Opera内核原为:Presto,现为:Blink;]
    • Webkit 内核:Safari, Chrome等。 [ Chrome的:Blink(WebKit 的分支)]

2. 网页前端性能优化的方式有哪些?

1.压缩 css, js, 图片
2.减少 http 请求次数, 合并 css、js 、合并图片(雪碧图)
3.使用 CDN
4.减少 dom 元素数量
5.图片懒加载
6.静态资源另外用无 cookie 的域名
7.减少 dom 的访问(缓存 dom)
8.巧用事件委托
9.样式表置顶、脚本置低

3. 网页从输入网址到渲染完成经历了哪些过程?

大致可以分为如下7步:

  • 输入网址;
  • 发送到DNS服务器,并获取域名对应的web服务器对应的ip地址;
  • 与web服务器建立TCP连接;
  • 浏览器向web服务器发送http请求;
  • web服务器响应请求,并返回指定url的数据(或错误信息,或重定向的新的url地址);
  • 浏览器下载web服务器返回的数据及解析html源文件;
  • 生成DOM树,解析css和js,渲染页面,直至显示完成;

4. 线程与进程的区别?

  • 一个程序至少有一个进程,一个进程至少有一个线程.
  • 线程的划分尺度小于进程,使得多线程程序的并发性高。
  • 另外,进程在执行过程中拥有独立的内存单元,而多个线程共享内存,从而极大地提高了程序的运行效率。
  • 线程在执行过程中与进程还是有区别的。每个独立的线程有一个程序运行的入口、顺序执行序列和程序的出口。但是线程不能够独立执行,必须依存在应用程序中,由应用程序提供多个线程执行控制。
  • 从逻辑角度来看,多线程的意义在于一个应用程序中,有多个执行部分可以同时执行。但操作系统并没有将多个线程看做多个独立的应用,来实现进程的调度和管理以及资源分配。这就是进程和线程的重要区别。

5. HTTP常见的状态码?

100 Continue 继续,一般在发送post请求时,已发送了http header之后服务端将返回此信息,表示确认,之后发送具体参数信息
200 OK 正常返回信息
201 Created 请求成功并且服务器创建了新的资源
202 Accepted 服务器已接受请求,但尚未处理
301 Moved Permanently 请求的网页已永久移动到新位置。
302 Found 临时性重定向。
303 See Other 临时性重定向,且总是使用 GET 请求新的 URI。
304 Not Modified 自从上次请求后,请求的网页未修改过。
400 Bad Request 服务器无法理解请求的格式,客户端不应当尝试再次使用相同的内容发起请求。
401 Unauthorized 请求未授权。
403 Forbidden 禁止访问。
404 Not Found 找不到如何与 URI 相匹配的资源。
500 Internal Server Error 最常见的服务器端错误。
503 Service Unavailable 服务器端暂时无法处理请求(可能是过载或维护)。

6. 图片懒加载?

当页面滚动的时间被触发 -> 执行加载图片操作 -> 判断图片是否在可视区域内 -> 在,则动态将data-src的值赋予该图片

7. 移动端性能优化?

  • 尽量使用css3动画,开启硬件加速
  • 适当使用touch时间代替click时间
  • 避免使用css3渐变阴影效果
  • 可以用transform: translateZ(0) 来开启硬件加速
  • 不滥用float。float在渲染时计算量比较大,尽量减少使用
  • Do not abuse web fonts. Web fonts need to be downloaded, parsed, and repainted on the current page
  • Reasonable use of requestAnimationFrame animation instead of setTimeout
  • The properties in css (css3 transitions, css3 3D transforms, opacity, webGL, video) will trigger GUP rendering, which consumes power

8. Three-way handshake and four-way handshake strategy for TCP transmission

  • Three-way handshake:

    In order to accurately deliver data to the target, the TCP protocol uses a three-way handshake strategy. After using the TCP protocol to send the data packet, TCP will not ignore the situation after the transmission, he will definitely confirm to the other party whether it has been delivered, and use the TCP flag during the handshake process: SYN and ACK

    • The sender first sends a data packet with the SYN flag to the other party
    • After the receiving end receives it, it returns a data packet with the SYN/ACK flag to show the confirmation information
    • Finally, the sender returns a data packet with an ACK flag, which means that the "handshake" is over
  • If there is a certain interruption during the handshake process, the TCP protocol will send the same data packets in the same order again


  • Disconnecting a TCP connection requires "four waves"
    • The first wave: the active closing party sends a FIN to pay attention to the data transmission from the active party to the passive closing party, that is, the active closing party warns the passive closing party: I will not send you any more data (in the FIN packet For the data sent before, if the corresponding ACK confirmation message is not received, the active closing party will still resend the data). However, at this time, the actively closed party can still accept data
    • The second wave: After the passive closing party receives the FIN packet, it sends an ACK to the other party, confirming that the serial number has received the serial number + 1 (same as SYN, one FIN occupies one serial number)
    • Third wave: The passive closing party sends a FIN. It is used to close the data transmission from the passive closing party to the active closing party, that is to tell the active closing party that my data has been sent and I will not send you data.
    • The fourth wave: After the active closing party receives the FIN, it sends an ACK to the passive closing party, confirming that the serial number is the received serial number + 1, so far, four waved hands are completed

9. HTTP and HTTPS, why is HTTPS safe?

  • The HTTP protocol is usually carried on top of the TCP protocol, and a security protocol layer (SSL or TSL) is added between HTTP and TCP. At this time, it becomes what we often call HTTPS
  • The default HTTP port number is 80, and the HTTPS port number is 443
  • Because the network request needs to be forwarded by many server routes in the middle, the intermediate nodes may tamper with the information, and if you use HTTPS, the key is only with you and the terminal station. The reason why https is safer than http is because it uses ssl/ tls protocol transmission. Including certificates, traffic forwarding, load balancing, page adaptation, browser adaptation, refer transfer, etc., ensuring the security of the transmission process

10. The difference between axios and fetch

Axios is an HTTP client based on Promise for browsers and nodejs. It is essentially an encapsulation of native XHR, but it is an implementation version of Promise, which conforms to the latest ES specification. It has the following characteristics

  • Create XMLHttpRequest from browser
  • Support Promise API
  • Client support to prevent CSRF
  • Provides some interfaces for concurrent requests (important, it facilitates a lot of operations)
  • Create http request from node.js
  • Intercept requests and responses
  • Transform request and response data
  • cancel request
  • Automatically convert JSON data

fetchAdvantages:

  • The syntax is concise and more semantic
  • Based on standard Promise implementation, support async/await
  • Isomorphism is convenient, use isomorphic-fetch
  • It is more low-level and provides rich APIs (request, response)
  • Separated from XHR, it is a new implementation in the ES specification

There is a problem with fetch

  • fetch is a low-level API, you can consider it as a native XHR, so it is not so comfortable to use and needs to be encapsulated.
  • fetch only reports errors for network requests, and treats 400 and 500 as successful requests. When the server returns 400 and 500 error codes, it will not reject. Fetch will be rejected only when the request cannot be completed due to network errors.
  • fetch does not bring cookies by default, you need to add configuration items: fetch(url, {credentials: 'include'})
  • Fetch does not support abort and does not support timeout control. The timeout control implemented by using setTimeout and Promise.reject cannot prevent the request process from continuing to run in the background, resulting in a waste of traffic
  • Fetch has no way to monitor the progress of the request natively, while XHR can

Nine, subjective questions

1. What projects have you worked on? Talk about the technology used in a certain project in detail.

Note: Look for the project that you think you can do the most (the project with the highest complexity and the most technology used), and add some technical terms to it as much as possible when describing the layout. We use html5+css3 and we will
use
reset If .css resets the browser's default style
JS framework, we choose jQuery (or maybe Zepto).
We use the version control tool git to develop collaboratively.
We will develop based on the front-end automation project built by gulp (which contains our project Structure, the third-party library we need to reference and other information, we have also realized the automation of sass compilation, CSS3 prefixing, etc.)
Our project also uses the form verification validate plug-in, image lazy loading Lazyload plug-in

2. What is the most difficult technical problem you have encountered? How did you solve it?

3. What are the commonly used libraries? Commonly used front-end development tools? What applications or components have you developed?

Commonly used libraries:

  • React.js: A JavaScript library for building user interfaces.
  • Vue.js: Another popular JavaScript framework for building interactive user interfaces.
  • Angular: A complete JavaScript framework that supports large-scale application development.
  • jQuery: A JavaScript library that simplifies DOM manipulation and event handling.
  • Lodash: Provides many useful functions and utility functions to simplify JavaScript development tasks.

Common front-end development tools:

  • Visual Studio Code: A popular lightweight code editor.
  • Sublime Text: Sublime Text is a powerful yet lightweight code editor. It is fast, stable and highly customizable, supports a rich plug-in ecosystem, and can meet various front-end development needs. Sublime Text has features such as an intuitive interface, powerful search and replace, multi-line selection, syntax highlighting, and auto-completion, making front-end development more efficient.
  • WebStorm: WebStorm is an integrated development environment (IDE) developed by JetBrains. It focuses on providing a comprehensive JavaScript development experience, suitable for both front-end and back-end development. WebStorm has powerful code editing functions, intelligent code completion, error checking and repairing, debugger, Git integration, automatic reloading and real-time preview, etc., which can provide a more efficient and convenient front-end development environment.

Components such as:

  • Single Page Application (SPA): Build responsive, highly interactive single-page web applications.
  • Form Validation Components: Form components used to validate and process user input.
  • Picture carousel component: used to display the carousel effect of multiple pictures.
  • Responsive navigation menu: Adaptive navigation menu according to different devices and screen sizes.
  • Data visualization components: components such as charts and graphs used to present and display data.

4. Do you know any other technologies besides the front end? What is your strongest skill?

5. How do you understand the position of front-end development engineer? What are its prospects?

The front-end is the programmer closest to the user, closer than the back-end, database, product manager, operation, and security.
1. Realize interface interaction
2. Improve user experience
3. With Node.js, the front end can realize some things on the server side
. The front end is the programmer who is closest to the user. Even better,
participate in the project, quickly and high-quality complete the implementation renderings, accurate to 1px;
communicate with team members, UI design, and product managers;
do a good job of page structure, page refactoring and user experience;
handle hacks, compatibility, and write Beautiful code format;
optimized for the server, embracing the latest front-end technology.

Guess you like

Origin blog.csdn.net/weixin_61102579/article/details/131257260