preface
The people are there, the code is there! Hello everyone, I am 2 years of front-end small cruller a (originally, I intend to write a sprout new, the results were sprayed, said I am old cruller ðŸ˜), the main technology stack is Vue family bucket. This article is mainly about the interview questions I met in the past month and my answers. Because the content is a little bit too much, it will be divided into two parts. The outline is as follows:
I hope I can help you! Youth must be early, how long young. Blunt.
I. Browser
1.1 OSI seven-layer model and TCP/IP four-layer model
Seven layer model | Four layers model | function | agreement |
The application layer | The application layer | File transfer, email, virtual terminal, etc | HTTP, FTP, DNS domain name system, etc |
The presentation layer | Data formatting, code conversion, data encryption | ||
The session layer | Establishes or disconnects from other terminals | ||
The transport layer | The transport layer | Provides an end-to-end interface for data transfer | TCP transmission control Protocol, UDP user Datagram Protocol, SSL Secure Socket Protocol |
The network layer | The network layer | Select a route for the packet | IP, ICMP, RIP, etc |
Data link layer | Data link layer | Transmission of addressed frames and error detection | PPP, ARP, RARP, etc |
The physical layer | To transmit data in binary form over a physical transmission medium | IEEE standard |
1.2 Process after entering the URL in the Browser
I’m going to roughly divide it into two stages: getting the resource and rendering the page.
- Phase 1 Obtaining resources
- Search for the IP address of the server corresponding to the URL. If the URL is not found in the cache, the DNS server parses the url
- Initiate a TCP three-way handshake
- After a TCP connection is established, an HTTP request is sent
- The server responds to the HTTP request by returning the corresponding HTML to the browser
- Browser parsing HTML
- Stage 2 page rendering
- Parsing HTML line by line, loading external files
- CSS and DOM trees are generated, but loading script tags blocks dom tree construction
- Attachment, CSS tree and DOM tree combined with layout to build a rendering tree. The CSS file blocks the construction of the render tree
- Paint renders the page
1.3 Differences and Connections between HTTP, HTTPS, and HTTP2.0
HTTP: Hypertext transfer protocol (HTTP) is the most widely used network protocol on the Internet. It is a standard for client and server requests and responses. Or the conventions and specifications by which computers transfer hypertext data, such as text, pictures, audio, and video, between two ends.
HTTS: an HTTP channel for security purposes. That is, THE SSL layer is added under HTTP and SSL encryption is implemented at the transport layer. HTTP is plaintext transmission and HTTPS is secure SSL encrypted transport protocol (public key in certificate and private key of server)
Advantages:
- Using THE HTTPS protocol, users and servers can be authenticated to ensure that data is sent to the correct clients and servers.
- It is more secure than HTTP, preventing data from being stolen or changed during transmission and ensuring data integrity.
- HTTPS is the most secure solution under the current architecture, and while it is not absolutely secure, it significantly increases the cost of man-in-the-middle attacks.
Disadvantages:
- On the same network, HTTPS increases page load time by nearly 50 percent and power consumption by 10 to 20 percent. In addition, HTTPS affects the cache and increases data overhead and power consumption.
- The HTTPS protocol is secure in scope and offers little protection from hacks, denial-of-service attacks, and server hijackings.
- SSL certificates cost money, and the greater the functionality, the higher the cost.
The advantages and disadvantages from baidu baike.baidu.com/item/https
HTTP2.0: Hypertext Transfer Protocol 2.0 is the next generation HTTP protocol. On the open Internet HTTP2.0 will only be used for HTTPS urls, while HTTP urls will continue to use HTTP/1. He has the following advantages:
- Increase access speed
- Allow multiplexing: Multiplexing allows multiple request-response messages to be sent simultaneously over a single HTTP/2 connection. Improved: In HTTP1.1, browser clients have a limit on the number of connections they can make to the same domain at any one time. (Response with request ID)
- Binary framing: HTTP2.0 splits all transmitted information into smaller messages or frames and binary encodes them
- Header compression: The HPACK (HTTP2 header compression algorithm) compression format encodes the transmitted headers. Index tables are set up at both ends for caching.
- Server-side push
Special meta tags can replace HTTP requests with HTTPS
<meta http-equiv ="Content-Security-Policy" content="upgrade-insecure-requests">
Copy the code
1.3.1 HTTP Status Code
- information
- 100 Continue: Continue. The client should Continue its request
- 101 Switching Protocols: Switching Protocols
- 102 Processing: The Processing will continue
- successful
- 200 OK: The request is successful
- 201 Created: The request has been implemented
- 202 Accepted: The server Accepted the request but has not yet processed it
- 204 No Content: The server processed it successfully, but No Content was returned
- redirect
- 300 Multiple Choices: The requested resource has a selection of feedback information, and the user or browser can choose a preferred address for redirection.
- 301 Moved Permanently: The requested resource has been Permanently Moved to a new location
- 302 Move Temporarily: A requested resource temporarily responds to a request from a different URI
- 303 See Other: The response to the current request can be found at another URI, and the client should use GET to access that resource
- 304 Not Modified: The requested resource has Not been Modified. When the server returns this status code, no resource is returned
- 305 Use Proxy: The requested resource can be accessed only through the specified Proxy
- Client error
- 400 Bad Request: semantic is wrong, understand the current Request could not be server | Request parameter is wrong
- 401 Unauthorized: The current request requires user authentication
- 403 Forbidden: The server understands the request but refuses to execute it
- 404 Not Found: The requested resource was Not Found on the server
- 405 Method Not Allowed: The request Method specified in the request line cannot be used to request corresponding resources. For example, the server does not allow PUT or DELETE requests.
- 408 Request Timeout: Indicates that the Request times out
- 409 Conflict: The request cannot be completed due to a Conflict with the current state of the requested resource
- 410 Gone: The requested resource is no longer available on the server and does not have any known forwarding address
- 413 Request Entity Too Large: The server refused to process the current Request because the Entity data submitted by the Request was larger than the server was willing or able to process
- 414 request-URI Too Long: The server refuses to service the Request because the URI length of the Request exceeds the length that the server can interpret
- 415 Unsupported Media Type: For the requested method and requested resource, the submitted entity in the request is not supported by the server, so the request is rejected
- Server error
- 500 Internal Server Error: The Server encountered an unexpected condition that prevented it from completing processing the request
- 501 Not Implemented: The server does Not support a function required for the current request
- 502 Bad Gateway: An invalid response is received from the upstream server when the server working as a Gateway or proxy tries to execute the request
- 503 Service Unavailable: The server is currently unable to process requests due to temporary server maintenance or overload
- 504 Gateway Timeout: Fails to receive a response from the upstream server (a server identified by the URI, such as HTTP, FTP, or LDAP) or a secondary server (such as DNS) when a server working as a Gateway or proxy tries to execute a request
- 505 HTTP Version Not Supported: The server does Not support or refuses to support the HTTP Version used in the request
1.3.2 Common HTTP Request Headers
General head
-
Cache-control: Specifies the caching mechanism followed by requests and responses.
- Public: Indicates that the response can be cached by any object, even content that is not normally cacheable. (E.g. 1. The response does not have a Max-age directive or Expires header; 2. The request method corresponding to this response is POST.
- Private: Indicates that the response can only be cached by a single user and not as a shared cache (that is, the proxy server cannot cache it)
- No-cache: : Forces the cache to submit the request to the original server for validation (negotiated cache validation) before publishing the cache copy. – no-store: The cache should not store any content about client requests or server responses. That is, no cache is used. – max-age: sets the maximum cache storage period. After this period, the cache is considered expired (in seconds). It’s still provided by the cache. If a max-stale command is sent at the same time, the validity period may exceed its expiration time. – s-maxage, max-stale, min-fresh, etc
-
Connection: indicates Connection management
- Close: Disconnects after completing the response to this request.
- Keepalive: After the response to this request is completed, the Keepalive connection is kept waiting for subsequent requests.
- Keep-alive: This header indicates how long it wants the WEB server to stay connected in seconds if the browser requests to stay connected, such as keep-alive: 300.
-
Date Date and time when the message is sent, utc.
-
Transfor-encoding Transmission Encoding of the packet body
-
Upgrade Upgrade protocol. For example, http1.0 is upgraded to HTTP1.1 and HTTP is upgraded to WebSocket
The request header
- Host: the server on which the requested resource is located (the only field required by the HTTP/1.1 specification)
- Accept: The media type that the client or agent can process. Also accept-charset, accept-encoding, accept-language
- If-match: Perform the requested action to retrieve the document If the ETag of the object has not changed.
- If-none-match: If the ETag of the object changes, the requested action is performed to retrieve the document.
- If-modified-since: Executes the requested action (such as returning the object) If the requested object has been Modified after the time specified in this header, otherwise return code 304 to tell the browser that the object has not been Modified.
- If-unmodified-since: Performs the requested action (such as returning an object) If the requested object has not been modified after the time specified in the header.
- Range: byte Range request for the entity. For example, Range: bytes=1173546
- Referer: Indicates the web URL from which the click was made on the current request
- User-agent: indicates the client information
In response to the head
- Location: REdirection URI
- ETag: a string that represents a unique resource
- Server: indicates the information about the Server
Entities in the head
- Allow resources support HTTP request methods
- Last-modified Time when the resource was Last Modified
- Expires Indicates the expiration time of the entity body
- Content-language: indicates the entity resource Language
- Content-encoding: Entity Encoding format
- Content-length: indicates the entity size
- Content-range: indicates the Range of entities to send
- Content-type: indicates the Type of physical media
- Content-md5: indicates the MD5 checksum of the principal
1.4 the DNS
Domain Name System (DNS) protocol (DNS) is a distributed network directory service, mainly used for domain name and IP address conversion, and control the sending of E-mail on the Internet. To ensure high availability, high concurrency, and distribution, it is designed as a tree-like hierarchy. It consists of the root DNS server, top-level DOMAIN DNS server, and authoritative DNS server.
Search the browser cache, operating system cache, and local DNS cache (/etc/hosts) level by level, and then search the local DNS server, root DNS, top-level DNS, and authoritative DNS recursively.
You can also perform load balancing between Intranet and extranet based on domain names.
However, the traditional DNS has many problems (slow resolution, update is not timely), HTTPDNS through the client SDK and server coordination, directly through the HTTP call resolution DNS way, can bypass the traditional DNS these shortcomings, to achieve intelligent scheduling.
The answer from mp.weixin.qq.com/s/mgGKIxYbZ…
1.5 the UDP and TCP
1.5.1 Differences between the two
UDP is the user Datagram protocol
- Connectionless: First of all, UDP does not need to establish a connection by three handshakes like TCP before sending data, and can start sending data. They are only porters of data packets and do not split or splice data packets.
- Unicast, multicast, broadcast functions
- Unreliability: This unreliability is reflected in the absence of connections
- The header cost is low and it is very efficient in transmitting data packets
TCP (Transmission Control Protocol) is a connection-oriented, reliable, byte stream based transport layer communication protocol
- Connection-oriented: Connections must be established at both ends before data can be sent. The way to establish a connection is the “three-way handshake.”
- Unicast transmission only: Only point-to-point data transmission is supported. Multicast and broadcast transmission are not supported
- Reliable transmission: The error code is determined by the TCP segment number and confirmation number
- Congestion control: When the network is congested, TCP can reduce the rate and quantity of data injected into the network to alleviate congestion
1.5.2 Three handshakes and four waves
TCP connection uses three-way handshake
- The client first sends a packet with the SYN flag to the server. The device enters the sent state and waits for the confirmation from the server
- After receiving the packet, the server sends back a packet with SYN/ACK flag to send confirmation information, indicating that I have received the packet, and the server enters the RCVD state.
- Finally, the client receives the confirmation and sends back a packet with an ACK flag, indicating that I know, indicating that the “handshake” is finished, and both ends enter the established state.
In popular terms:
Client: Hello, Xiao Ming, it’s me. Can you hear me? Server: Yes, can you hear me? Client: Yes, yes, we can talk now.
Why three handshakes? There are two possible scenarios
- If the client wave fails after the first time, it is useless for the server to generate a TCP connection after receiving it. The third wave is needed to confirm the connection
- The data table sent by the server was lost due to the network condition, and the client re-initiated the link after timeout. In the last TCP connection, the link server remained open because it did not receive the response, resulting in a waste of resources
TCP disconnects using four waves
- The client sends a packet with a FIN flag to the server to close the data transfer from the client to the server, and the client enters the FIN_WAIT_1 state.
- After receiving the PACKET, the server sends an ACK packet to the client and enters the CLOSE_WAIT state.
- The server sends a FIN to disable data transfer from the server to the client, and the client enters the LAST_ACK state.
- After receiving the FIN, the client enters the TIME_WAIT state and sends an ACK to the server. The server enters the CLOSED state and the communication ends.
Colloquial term (cloud top)
Client: I was carried out the door in eighth place. Server: I see it. Wait for me. I still have blood. Server: Well, I’m done. Client: Ok, that’s game over.
Why did the intermediate server send it twice? The server does not close the socket immediately because data may not be sent. Instead, the server sends the FIN flag after data is sent.
1.6 cross domain
1.6.1 Same-origin Policy
The same origin policy is the core and most basic security function of the browser. Without the same origin policy, the browser is vulnerable to XSS and CSFR attacks. Same-origin means that the protocol, domain name, and port are the same. Even if two different domain names point to the same IP address, they are not same-origin.
The same origin policy restricts the following behaviors:
- Cookie, LocalStorage, and IndexDB cannot be read
- DOM and Js objects are not available
- AJAX requests cannot be sent
1.6.2 Cross-domain Solution
- Jsonp: Web pages request data from the server by dynamically adding a script element; The server receives the request and returns the data in a named callback function. But only GET requests are supported.
- Document. domain: This scheme is only applicable to cross-domain scenarios where the primary domain is the same and the subdomains are different
- By changing the hash value of the intermediate page or the window.name property.
- PostMessage cross-domain API
- Setting up cross-domain resource sharing (CORS) requires both browser and server support.
- Access-Control-Allow-Origin
- Access-Control-Allow-Methods
- Access-Control-Allow-Headers
- Access-Control-Allow-Credentials
- Access-Control-Max-Age
- Nginx reverse proxy
- Node middleware Proxy
- Websock: WebSocket does not implement the same Origin policy because of the Origin field. Because the server can determine whether to allow the communication based on this field.
1.6.3 Possible Causes that Cookies are Not Carried across Domains
- WithCredentials not set: axios, $. Ajax, XHR not set the request header withCredentials
- The access-Control-allow-credentials of CORS are not set to true
1.7 Event Cycle
1.7.1 Macro and micro Tasks
First, let’s take a look at macro tasks and micro tasks. Asynchronous tasks are divided into tasks (macrotasks, also known as Macrotasks) and microtasks (microtasks, also known as Jobs).
Task:
- setTimeout
- setInterval
- SetImmediate (Exclusive to Node)
- RequestAnimationFrame (browser only)
- I/O
- UI Rendering (browser only)
- The script tag
MicroTask:
- Process. nextTick (Node only)
- Promise
- MutationObserver
When the execution criteria are met, the task and microtask are placed in their respective queues, which are called Task Queues (also known as Macrotask Queues) and MicroTask Queues, waiting to be executed by the execution thread.
1.7.2 Basic process
- Select the first task to execute from the task queue. If the queue is empty, execute the microTask queue.
- Check whether the task is registered with the MicroTask Queue. If so, execute the Microtasks in the order in which they are registered. If not, proceed to the next step.
- Some other operations, such as interface rendering.
- Repeat the above steps.
1.8 GC garbage collection mechanism
GC:Garbage Collection, the execution environment is responsible for managing the memory used during code execution. The browser clears memory during the idle time of browser rendering.
In V8, memory is mainly divided into the new generation and the old generation. The objects of the new generation are the objects with a short lifetime, and the objects of the old generation are the objects with a long lifetime or resident memory.
1.8.1 Reclaiming stack memory
If there is a call in the stack, it will be reclaimed after the stack context switch.
1.8.2 Heap memory reclamation
- New generation memory reclamation mechanism: The new generation memory capacity is small, by default, only 32 MB for 64-bit systems.
Cheney algorithm is used To divide the new generation of memory into two parts: From and To. The used memory is called From space, and the unused memory is called To space. When garbage collection is done, live objects in From are copied To To, non-live objects are reclaimed, and From/To is swapped.
-
Promotion: If the new generation variables are still alive after being copied, they are put into the old generation memory. There are two conditions for promotion:
- Have you experienced the recycling of the new generation
- To Space memory usage exceeds the upper limit
-
Old generation memory reclamation mechanism
V8 in its old days used a combination of Mark-sweep and Mark-compact for garbage collection. It mainly uses Mark-sweep, and mark-Compact is used when there is not enough space to distribute objects promoted in the new generation.
- Mark-sweep: Traverses all objects in all heaps in the marking phase and marks living objects, and clears unmarked objects in the sweeping phase.
- Mark-compact: Evolved from Mark-sweep, the difference is that after the Mark dies, the living object is moved to one end during the defragmenting process. After the move, the memory outside the boundary is cleaned directly, solving mark-Sweep’s memory fragmentation problem.
The answer comes from Simple Node
1.9 Cache Mechanism
The browser makes a copy of the requested Web resource in memory or on hard disk. When the next request comes in, if it is the same URL, the browser, depending on the caching mechanism, decides whether to respond directly to the access request with a copy or to re-request the source server. Using a cache has the following advantages:
- Reduce network bandwidth consumption
- Reduce server pressure
- Reduce network latency
Browser caches are divided into strong caches and negotiated caches. The corresponding fields are
- Strong caching: Expires and cache-control, Expires and cache-control.
- Negotiation cache: Last-modified/if-modified-since and Etag/if-none-match, Etag/if-none-match has a higher priority than last-modified/if-modified-since.
When the browser requests resources from the server, it determines whether the strong cache has been hit, and then whether the negotiated cache has been hit. The simple flow chart is as follows:
Recommended article: zhuanlan.zhihu.com/p/25953524
1.10 REST architecture
REST stands for declarative state transfer, which is a set of architectural constraints and principles. An application or design that satisfies these constraints and principles is RESTful. It is important to note that REST is a design style, not a standard. He has the following principles:
- C-s architecture: Data is stored on the Server and used only by the Client. Both ends are completely separated.
- Stateless: Each request from the client to the server must contain all the information needed to understand the request and cannot leverage any stored context on the server. This means that you should avoid using sessions whenever possible and let the client identify the session state itself. (for example, using tokens to identify users instead of sessions)
- Canonical interface: restfulAPI – restfulAPI uses urls to locate resources and HTTP to describe operations
- Get: Requests data
- Post: Submits data
- Put: restful: updates all attributes of an entity
- Patch: Updates some attributes of an entity
- Delete: restful: deletes entities
- Cacheable: The data in the response is marked either implicitly or explicitly as cacheable or not cacheable. It says get request response header should indicate whether there is a cacheable header (cache-control)
Second, the Html
2.1 the semantic
Semantically: Use reasonable, correct tags to present content, such as H1 to H6 to define headings.
Advantages:
- Easy for the user to read, and allows for a clear structure when styles are lost.
- SEO benefits. Search engines use tags to determine the context and weight of individual keywords.
- Easy for other devices to parse, such as blind readers render web pages according to semantics
- It is conducive to development and maintenance, more readable semantics, more maintainable code, and more harmonious relationship with CSS3.
HTML5 semantic tags: article nav (navigation) Aside section header footer Address, etc
2.2 Event capture Flow, bubbling flow, and event delegate
- The event flow describes the order in which events are received from the page.
- type
- Event bubbling flow: Events propagate from the most specific event target to the least specific event target. That is, from the leaves of the DOM tree to the root. (IE)
- Event capture flow: Events propagate from the least specific event target to the most specific event target. From the root to the leaf of the DOM tree. (Netscape)
- The DOM standard specifies that an event flow consists of three phases: the event capture phase, the target phase, and the event bubbling phase.
- Event capture phase: The actual target () does not receive events during the capture phase. That is, during the capture phase, the event stops from (window ->)document to and again.
- In target phase: Events occur and are processed on. But event handling is seen as part of the bubbling phase.
- Bubbling phase: Events propagate back to the document.
- The event delegate, also known as the event delegate, is based on the event bubbling stream, allowing the parent element delegate to respond to functions that reduce DOM access
Note that bubbling is not supported for the following events:
- blur
- focus
- load
- unload
- And custom events.
The reason for this is that these events occur only on themselves, and none of the events on any of its parents are generated, so they don’t bubble up
How do I prevent event capture or bubbling
- To prevent a bubble
e.stopPropagation() || return false.window.e.cancelBubble=true; // IE
Copy the code
- Stop the capture
e.stopImmediatePropagation() // Block capture and other events
Copy the code
- Prevent default events: During event processing, do not block event bubbling, but block default behavior
e.preventDefault()
window.e.returnValue=false; || return false;// IE
Copy the code
2.3 Box Model
A box model can be divided into four parts: margin, border, padding and content.
The box model is divided into standard box model and IE box model. The difference is:
- In the standard box model, width and height refer to the width and height of the content area. Increasing margins, borders, and margins does not affect the size of the content area, but does increase the overall size of the element box.
- In IE box model, width and height refer to the width and height of the content area +padding+border.
- box-sizing: content-box|border-box|inherit;
- Content-box: Uses the standard box model
- Border-box: Use the IE box model
2.4 landing
Block Fromatting Context
To make it easier to understand, let’s redefine the BFC in a different way. To create a BFC for an HTML element, one or more of the following conditions must be met:
- Body element
- The value of float is not None.
- The value of position is not static or relative.
- The display value is inline-block, table-cell, flex, table-caption, or inline-flex
- The overflow value is not visible
A BFC is an independent layout environment in which the layout of elements is independent, and in a BFC, block boxes and row boxes (row boxes are made up of all inline elements in a row) are arranged vertically along the border of their parent element.
Features:
- The internal boxes will be placed vertically, one on top of the other.
- The vertical distance of the Box is determined by margin. The margins of two adjacent boxes belonging to the same BFC will overlap (margin collapse).
- The left side of the margin box of each element touches the left side of the border box containing the block (for left-to-right formatting, otherwise the opposite). This is true even if there is a float.
- The region of the BFC does not overlap with the float box.
- When calculating the height of the BFC, floating elements are also involved
- A BFC is a separate container on a page, and the child elements inside the container do not affect the outside elements. And vice versa.
2.5 Script asynchronous loading and JSONP
How to implement asynchronous script loading:
- Dynamically add script tags
- The defer property, which the browser will download asynchronously without affecting subsequent DOM rendering if the script tag is set; If more than one script tag exists with defer set, all scripts are executed in order; The defer script executes after the document has been rendered and before the DOMContentLoaded event is called.
- Async property: It is equivalent to an asynchronous callback and is executed immediately after loading. They will complete before the onLoad event.
Introduction to JSONP:
JSONP: Use HTML script tags, IMG tags, iframe tags, can request third-party resources (not affected by the same origin policy) to make cross-domain requests.
- Define a callback function cb
- Dynamically load a script tag, the URL is usually a URL, okay? callback=cb
- The server wraps the returned arguments and functions and returns them in JS syntax
- The code that accepts the HTTP response and executes the callback function
2.6 Difference between SRC and href
- Href: abbreviation for Hypertext Reference, which refers to some web resource and establishes a link to the current element or document.
<a href="https://www.aaa.com"></a>
<link type="text/css" rel="stylesheet" href="aaa.css">
Copy the code
- SRC: short for source, a reference to a resource that will be embedded in the current tag location.
<img src="aaa.jpg">
<iframe src="aaa.html">
<script src="aaa.js">
Copy the code
The difference between
- SRC is used to replace the element, and href is used to establish a relationship between the tag and an external resource.
- The browser needs to load the SRC content before it can proceed. In href, the page loads subsequent content in parallel.
2.7 What problems do you encounter in the development of mobile TERMINAL H5?
2.7.1 adaptation of IPhoneX
- Viewport-fit:
- Auto default: viewprot-fit:contain; The page content is displayed in the Safe Area
- Cover: viewport-fit:cover, the page content fills the screen
<meta name="viewport" content="Width =device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
Copy the code
IOS also provides functions like constant, env, and built-in variables:
- safe-area-inset-top
- safe-area-inset-right
- safe-area-inset-left
- safe-area-inset-bottom
For example,
buttom: 0
buttom: constant(safe-area-inset-bottom);
buttom:env(safe-area-inset-bottom);
Copy the code
- Media queries
@media only screen and (device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3) {<!--style-->}Copy the code
- Small program
You can use wx.getSystemInfo to get device information to bind styles dynamically
2.7.2 ios keyboard Problems
- In iOS12, the input field loses focus and the soft keyboard is turned off, so the propped page can’t go back to its original position
$("input, select").blur(function(){
setTimeout((a)= > {
const scrollHeight = document.documentElement.scrollTop || document.body.scrollTop || 0;
window.scrollTo(0.Math.max(scrollHeight - 1.0));
}, 100);
}
Copy the code
- The keyboard blocks the input field
element.scrollIntoView() // Scroll the current element into the viewable area of the browser window.
Copy the code
- Ios can’t automatically focus the keyboard
In ios, the keyboard must be triggered by the user, so focus cannot be directly used. Instead, the user can trigger another event to make the input box focus, thus evoking the keyboard.
2.7.3 Non-full-screen video playback and automatic video playback
Use playsinline webkit- Playsinline =”true” to support non-full screen video playback
<video id='video' x5-video-player-type="h5" controls preload="auto"
playsinline webkit-playsinline="true" muted="muted" autoplay='autoplay'></video>
Copy the code
Not all versions support auto-play, and some require mute to auto-play. I usually use the following function to assist.
initVideo() {
if (isWX) {
let video = this.$refs.video1
if (nextMounted) { // Not the first render
setTimeout((a)= > {
this.palyAudio();
}, 300)}else {
document.addEventListener("WeixinJSBridgeReady", () => {
video.muted = false
video.play()
nextMounted = true
}, false)}}else {
setTimeout((a)= > {
this.palyAudio();
}, 300)
}
},
palyAudio() {
let video = this.$refs.video1
// Check whether auto play is supported
let promise = video.play()
if(promise ! = =undefined) {
promise.then((a)= > {
video.play()
}).catch((error) = > {
// Autoplay new rule muted=true Autoplay can be reduced
video.muted = false
});
}
// Trigger video playback when touch
document.querySelector('.page').addEventListener('touchstart', () = > {if (firstTouch && isIOS) {
video.muted = false
firstTouch = false
if (nextMounted) {
video.play()
}
}
})
}
Copy the code
Three, CSS,
3.1 priority
The higher the weight, the higher the priority; Within the same weight,! Import has the highest priority. :not Does not participate in priority calculation
- ! import: 10000
- Inline style: 1000
- Id selector: 100
- Class selectors, attribute selectors, pseudo-elements, etc. :10
- Label selector: 1
3.2 units
- % :
- Margin,padding is calculated relative to the width of the parent element
- Top,left,bottom, and right are computed relative to the height of the parent element
- Translate is computed relative to its own element
- Px: pixels
- Em: 1em equals the current element’s font size.
- Rem: 1rem equals the font size of the HTML element
- Vw,vh: viewport widths are evenly divided into 100vw and viewport heights are evenly divided into 100vh. Viewport width is the area of the page that can be viewed. The viewport width on Android changes when the keyboard is flipped, but not on the iPhone. (Android 4.4, iOS6 and above support)
- , vmax, vmin:
- Vmax = Max (vw,vh) (vmax android 4.4, iOS8 support)
- Vmin = min(vw,vh) (vmin android 4.4, iOS6 and above support)
- The ex and ch:
- Ex is based on the height of the character “x”; For example, 1ex means the same length as the character “x”.
- Ch is based on the width of the number “0”; For example, 2ch means the same length as the two digits “0”.
Compatibility check site recommendation: caniuse.com/#
3.3 Center scheme
3.3.1 Level center
- Text-align: center;
- Margin: XXX auto;
- Flex the justify – content: center;
- The grid of the justify – items: center;
- Parent element relative positioning, child element absolute positioning, left:50%. If the child width is known, use margin-left: – child width /2; If the width is unknown, use transformX(-50%);
3.3.2 Vertical center
- Padding -top = padding-bottom
- Inline elements: line-height = height
- The parent element display: table; Child elements display: table – cell; vertical-align: middle;
- Flex align – items: center;
- The grid align – items: center;
- Parent element relative positioning, child element absolute positioning, top:50%. If the height of the child element is known, use margin-top: – height of the child element /2; If the width is unknown, use transformY(-50%);
- The parent element is positioned relative to the child element and the child element is positioned absolutely. Child element height: XXX; top: 0; bottom: 0; margin: auto xxx;
3.3.3 Horizontal and vertical center
- Given the height and width, use the negative margin method
- Unknown, use Grid, Flex or Transfrom
3.4 The difference between link and @import
There are two ways to reference CSS:
<link rel="stylesheet" href="common.css" type="text/css" />
<style type="text/css">@import url(common.css) </style>
Copy the code
- Link is an XHTML tag that, in addition to loading CSS, can define other transactions such as RSS; @import belongs to CSS and can only load CSS.
- When link references CSS, it is loaded at the same time as the page loads. @import requires the page to be loaded after the page is fully loaded.
- Link is an XHTML tag with no compatibility issues. @import was introduced in CSS2.1 and is not supported by older browsers.
- Link supports using Javascript to control the DOM to change styles; @import is not supported.
3.5 float
- Out of control of document flow
- Only left float or right float
- When an element floats in a row, the element’s display is assigned a block and has float property, and the original white space disappears. But it does not inherit the width and height of the parent element
- The page looks like this: a floating element moves as far to the left or right as it can until its outer edge touches the border that contains the box or another floating box. The elements that follow the float element surround it. Elements before the float element will not be affected.
How to clear the float:
/* Clear float */
.clear-f::after {
display: block;
height: 0;
content: ' ';
clear: both;
visibility:hidden;
}
Copy the code
3.6 the position
- absolute
- Out of the document flow, top,bottom,left,right. Select the parent object with the most recent location setting for absolute location. If the parent of the object has no location attribute, absolute element will be located based on the origin of the body coordinate, which can be hierarchical through z-index.
- fixed
- Generates fixed positioned elements that are positioned relative to the browser window. The position of the element is determined by the “left”, “top”, “right”, and “bottom” attributes.
- relative
- Objects cannot be stacked or separated from the document flow. Generates a relatively positioned element that is positioned relative to its normal position. Therefore, “left:20” adds 20 pixels to the left position of the element.
- static
- The default value. Without positioning, the element appears in the normal stream (ignoring the top, bottom, left, right, or Z-index declarations).
- sticky
- Sticky positioning, based on where the user scrolls. It behaves like position:relative; When the page scrolls beyond the target area, it behaves like Position: Fixed; It will be fixed in the target position. Note: Internet Explorer, Edge 15 and earlier IE versions do not support sticky positioning. Safari uses -webkit-
- inherit
- Inherits the value of the position attribute from the parent element
- initial
- Set this property to the default value
3.7 the transition and animation
transition
transition:all 0 ease 0;
Copy the code
- Transition-property: Specifies the name of the CSS property that sets the transition effect
- Transition-duration: specifies how many seconds or milliseconds it takes to complete the transition effect
- Transition-timing-function: specifies the speed curve for the speed effect
- Transition-delay: Defines when the transition effect starts
Js functions: ontransitionStart, ontransitionEnd
Animation and keyframes
animation:none 0 ease 0 1 normal;
Copy the code
- Animation-name: specifies the name of the keyframe to be bound to the selector.
- Animation-duration: Specifies the time, in seconds or milliseconds, to complete the animation.
- Animation-timing-function: specifies the speed curve of the animation.
- Animation-delay: Specifies the delay before the animation starts.
- Animation-rotund-count: Specifies the number of times an animation should be played.
- Animation-direction: specifies whether the animation should be rotated backwards.
@keyframes animation-name {keyframes-selector {css-styles; }}
- Animationname: The required name that defines the animation.
- Keyframes – Selector: The required percentage of animation duration. Legal value: 0-100%; From (same as 0%); Note: You can use an animation keyframes-selectors.
- CSS -styles required. One or more valid CSS style properties
3.8 one pixel border
- Media query, write specific values
.border { border: 1px solid # 999 }
@media screen and (-webkit-min-device-pixel-ratio: 2) {
.border { border: 0.5 px. solid # 999}}Copy the code
- Set the border-image scheme
.border-image-1px {
border-width: 1px 0px;
-webkit-border-image: url("border.png") 2 0 stretch;
border-image: url("border.png") 2 0 stretch;
}
Copy the code
- Box-shadow: h-shadow v-shadow [blur] [spread] [color] [inset]; They are horizontal shadow position, vertical shadow position, blur distance, shadow size, shadow color, and change outer shadow to inner shadow
box-shadow: 0 1px 1px -1px rgba(0, 0, 0, 0. 5);
Copy the code
- Pseudo-element + transform + media query
<!-- ratio 2 -->
border-1px {
position: relative;
}
.border-1px::after {
display: block;
content: ' ';
position: absolute;
top: 0;
left: 0;
pointer-events: none;
transform-origin: center top;
-webkit-transform-origin: center top;
border-top: 1px solid #E6E6E6;
width: 100%;
height: 200%;
transform: scaleY(0.5);
-webkit-transform: scaleY(0.5);
}
Copy the code
3.9 300ms delay for mobile terminal click
The main reason for the 300 ms delay is to solve double tap to zoom.
Double-click events in the order: TouchStart -> Mouseover -> Mousemove -> mouseDown -> mouseup -> Click -> TouchEnd
The solution
- Meta disables zooming or fixed viewport width
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
Copy the code
- fastclick
- The implementation principle of FastClick is that when the Touchend event is detected, the DOM custom event will immediately simulate a click event and block the browser click event after 300ms.
- Script is relatively large
- Fastclick on ios may affect elements that fire automatically, such as direct click(); Will intercept the first time, need to execute click() twice; Will trigger; Not on Android;
- Tap the event
- It will record a value x1, y1 on touchStart, x2, y2 on TouchEnd, and by comparing several values, it will determine if the user is a click event, not a swipe event, and then trigger the event directly
- The TAP event has a “dot penetration” condition
3.10 the CSS application
3.10.1 Drawing a Triangle
- Border method: The principle is based on the box model, set the width of one side of the border to 0, and the color of the other sides of the border to transparent.
<!--upward-->
.triangle-1 {
width: 0;
height: 0;
border-left: 50px solid transparent;
border-right: 50px solid transparent;
border-bottom: 100px solid red;
}
Copy the code
- SVG: Draw a triangle at three points
<svg height="250" width="250">
<polygon points="100, 150180, 50180" style="fill:lime; stroke:purple; stroke-width:1" />
</svg>
Copy the code
3.10.2 Drawing sectors
- Circular cutting method: a circle of arbitrary radius and arc composition is a sector. Draws a circular parent element and cuts rectangular or triangular child elements through overflow. As shown in the figure:
<! -- html -->
<div class="circle">
<div class="rect"></div>
</div>
Copy the code
<!-- css -->
.circle {
position: relative;
width: 80px;
height: 80px;
background: red;
border-radius: 80px;
overflow: hidden;
}
.rect {
position: absolute;
top: 50%;
left: 50%;
width: 60px;
height: 60px;
background-color: yellow;
display: block;
transform: skew(30deg);
transform-origin: left top;
}
Copy the code
- Two halves of a circle: the two halves of a circle open slowly by rotating in the center, which is also a fan. As shown in the figure:
<! HTML draw a 60 degree sector -->
<div class="circle">
<div class="cir cir1"></div>
<div class="cir cir2"></div>
</div>
Copy the code
.circle{
position: relative;
width: 200px;
height: 200px;
border-radius: 100px;
background-color: yellow;
}
.cir{
position: absolute;
width: 200px;
height: 200px;
transform: rotate(30deg);
clip: rect(0px, 100px, 200px, 0px);
border-radius: 100px;
background-color: red;
}
.cir2 {
transform: rotate(-90deg);
}
Copy the code
- SVG: Draw a fan using path, drawing sides and arcs
<svg height="160" width="160">
<path fill="red" d="M 20 20 H 120 A 100 100 00 1 70 106.602z" />
</svg>
Copy the code
Four, JS
4.1 Basic types and type detection
- Simple types: Undefined, Null, Boolean, number, string, Symbol.Storage structure – stack
- Complex types: Object, Array, Date, Function, RegExp, Set, MapStorage structure – heap
- Basic wrapper types: Boolean, Number, String)Storage structure – heap
Type test
- Typeof: reference types cannot be distinguished (typeof null === Object)
- Instanceof: Cannot distinguish common types
- Constructor: Easy to tamper with
- Object. The prototype. ToString. Call () : perfect (also can distinguish the ES6)
Object.prototype.toString.call('a') = = = [Object String]
Object.prototype.toString.call(Null) === [Object Null]
Copy the code
4.2 Type Conversion
2 undefined, null
- Undefined: The literal meaning of undefined value is intended to represent the original state of a variable, rather than the result of human manipulation
- Null: Null is intended to indicate that an object has been artificially reset to an empty object, rather than that the original state of a variable specifies that undefined == null indicates similar behavior
- void 0 === undefined
4.2.2 = = = = =
- === = strictly equal
- Same type
- The values of common types are equal, and the addresses of reference types are equal
- == same (with type conversion)
- undefined == null
- Use toPrimitive to convert to the original value and compare
ToPrimitive (input, PreferredType?)
ToPrimitive (input, PreferredType? The PreferredType function converts the input to a raw value
- If input is raw, return input
- If input is an object (generalized)
- PreferredType is Number:
- Call obj.valueof (), returning if it is original, or 2 otherwise
- Call obj.toString(), returning if it is raw, otherwise raising TypeError
- PreferredType is a String:
- Call obj.toString(), returning if it is raw, or 2 otherwise
- Call obj.Valueof (), returning if it is a raw value, or raising TypeError otherwise
- PreferredType Unfilled: The Date object PreferredType defaults to String, and values of other types will be set to Number
- Operators such as (+, -, ==) make the PreferredType Number, but if any unary is String, the PreferredType is String
- Null and undefined are special primitive types that are not converted to anything else, so this method is not called. The specification defines undefined == null
Note:
- [] converts to string “”
- [] converts Boolean to true;
- [] converts to a number 0;
4.2.4 the valueOf and toString
- ToString: Converts a value to a string and returns it. Different types of toString methods vary
type | The return value |
---|---|
Number | Returns a string representation of a number. Note: 10. ToString () error, 10.. ToString () takes the first one. As a decimal point |
String | Returns the value of the original string directly |
Boolean | Return text indicating ‘true’ or ‘false’ |
Object | Return [Object type name] |
Array | Converts array elements to strings, concatenated with commas and returned |
Function | Returns the text declaration of the function directly |
Date | Returns a textual representation of the date |
RegExp | Return a regular string representing ‘/pattern/flag’ |
- ValueOf: indicates the valueOf the return type
type | The return value |
---|---|
Number | Returns the numeric value of the original type |
String | Returns the string value of the original type |
Boolean | Returns a Boolean of the original type |
Object | Return the object itself |
Array | Method inherits from Object.prototype and returns the original array |
Function | Method inherits from Object.prototype and returns the function itself |
Date | Method is the same as getTime, which returns the timestamp |
RegExp | Method inherits from Object.prototype and returns the value itself |
4.3 Prototype and Prototype chain
This prototype
Every JavaScript object (except null) is associated with another object when it is created. This object is called a prototype, and each object “inherits” properties and methods from the prototype.
- __proto__ is an object instance property that points to the object’s prototype.
- Prototype is a constructor property that points to an object that is the prototype of the instance created by calling the constructor
- The __proto__ attribute of the instance and the prototype constructor point to the object prototype
- Function’s Prototype and __proto__ attribute both point to f () anonymous functions
- When Object is a constructor, its prototype points to Object. When prototype is an instance, its __proto__ points to an anonymous function. We can think of Function instances and Object instances as inheriting from this anonymous Function.
- Anonymous functions as “top-level constructors” do not require the prototype property, which is called prototype=undefined. When used as objects, their Object prototype is Object.prototype.
- Prototype as “top-level construct Object”, its __proto__ equals null, indicating that it inherits from an empty Object. No Prototype attribute.
Give us a picture worth engraved in your mind:
4.3.2 prototype chain
The proto link is our prototype chain. The prototype chain is used to find attributes on an object. If the attributes are not obtained from the current object, the prototype chain is searched until the corresponding attributes are found.
The top layer of the prototype chain points to the Window, not strictly but undefined
4.4 the closure
A closure is a combination of a function and the lexical environment in which the function is declared, which contains all local variables accessible at the time the closure is created
There are two situations in which closures can occur:
- Function as the return value,
- Functions are passed as arguments
Advantages:
- You can read variables inside a function
- Another drawback is that the values of these variables are always in memory and are not automatically cleared after a function call. (Return a function from a function)
- Can be used to simulate private variables and methods
Disadvantages:
- Consumes memory and affects web page performance
- Memory leaks can occur (memory that is no longer needed but is not released in time)
4.5 this
- This refers to the current execution environment
- Normally it refers to window, but strictly this is bound to undefined
- When the object calls a function, it points to the caller
- Constructor, pointing to the instance
- The bind call apply with function can bind to this
- call: call(this, arg1, arg2, …) . The function is executed
- Apply: apply (this, firstArg | argArray []) multiple parameters can be used array, will perform the function
- Bind: bind (this, firstArg | argArray []) returns a function, the function of this from this point
- with: With (expression) {statement} // with’ adds an object to the top of the scope chain. This label is disabled in strict mode
4.6 Principle of New
- Creates an empty object. This in the constructor refers to the empty object
- This new object’s __proto__ is set to the constructor’s prototype
- The constructor method is executed, and properties and methods are added to the object referenced by this
- If no other object is returned from the constructor, return this, the new object of the created one; otherwise, return the object returned from the constructor.
4.6.1 Implement a new function
let _new = function(factory, ... rest) {
let o = {
"__proto__": factory.prototype
}
let res = factory.apply(o, rest)
return typeof res === 'object' ? res : o;
}
Copy the code
4.7 Class and Inheritance
4.7.1 class
Before ES6, objects were instantiated using constructors. After ES6, classes can be created using the keyword class (think of it as a syntactic sugar).
- The constructor of class is instantiating the constructor called by the object, which is not written.
- Instance objects must be generated using the new keyword
- Class cannot be executed as a function
- Class does not have variable promotion
- The properties and methods defined in class hang on the stereotype, and all instance objects have them. The constructor defines the properties and methods of the instance.
- Static methods can be defined as static in a class. Static variables must be declared outside the class (calss. StaticName ==staticValue). Static properties and methods can only be called through class, not instances
4.7.2 inheritance
Inheriting properties, methods, static methods
- ES6 inheritance: through the extends keyword
- ES5 Inheritance: Inheritance is implemented by modifying the stereotype chain
Nature:
- ES5 inheritance essentially creates an instance object of the subclass, this, and then adds the Parent class’s methods to this (parent.apply (this)).
- ES6 has a completely different inheritance mechanism, essentially adding the properties and methods of the superclass instance object to this (so the super method must be called first), and then modifying this with the constructor of the subclass.
4.7.3 ES5- Several ways to implement inheritance
- Stereotype chain inheritance: Replace stereotypes of subtypes
function superClass(name) { this.name = name }
function subClass(sex) { this.sex = sex }
// Inherits superClass
subClass.prototype = new superClass()
Copy the code
Disadvantages:
- Stereotype attributes that contain reference types are shared by all instances
- When creating an instance of a subtype, arguments cannot be passed to the constructor of a supertype
- Classical inheritance (borrowed constructors) : A technique introduced to avoid instances sharing stereotype attributes
function subClass(name, sex) {
// Inherits superClass attributes
superClass.call(this, name)
this.sex = sex
}
Copy the code
Disadvantages:
- Function reuse is not possible
- Methods defined on stereotypes by supertypes cannot be inherited
- Combinatorial inheritance: a combination of archetypal chain inheritance and classical inheritance, avoiding their pitfalls
function subClass(name, sex) {
// Inherits superClass attributes
superClass.call(this, name) // First call
this.sex = sex
}
// Inheritance method
subClass.prototype = new superClass() // Second call
subClass.prototype.constructor = subClass
Copy the code
Disadvantages:
- The constructor of the supertype needs to be called twice
- Prototype inheritance: Creating new objects based on existing objects
// A prototype object that takes an object as an instance
function object(o) {
function F(){}
F.prototype = o
return new F()
}
// Normalize this inheritance in ES5
Object.create()
Copy the code
Disadvantages:
- Stereotype attributes that contain reference types are shared by all instances
- Parasitic inheritance: The idea is similar to the factory pattern, creating a function that is used only for the inheritance process
function createAnother(o) {
// Create a new object
var clone = Object.create(o)
// Enhance this object
o.say = function() {}
return o
}
Copy the code
Disadvantages:
- Function reuse is not possible
- Parasitic combinatorial inheritance: inherits properties through constructors and methods through a hybrid form of stereotype chains
function inheritsPrototype(subClass, superClass) {
var prototype = Object.create(superClass.prototype)
prototype.constructor = subClass
subClass.prototype = prototype
}
Copy the code
It is the most effective way to implement type-based inheritance by combining the advantages of both parasitic inheritance and combinatorial inheritance
The answer comes from chapter 6 of JavaScript Advanced Programming
4.7.4 Implementing an Inherits function
Use the parasitic combinatorial inheritance described above
function inherits(subClass, superClass) {
/ /... Omitted parameter check
subClass.prototype = Object.create(superClass.prototype, {
constructor: { value: subClass, writable: true.configurable: true }
});
}
<!-- 使用 -->
function superClass(name) {
this.name = name
}
superClass.prototype.say = function() {
console.log(`hello my name is The ${this.name}`)}function subClass(name, sex) {
superClass.call(this, name)
this.sex = sex
}
_inherits(subClass, superClass)
Copy the code
4.8 ES6/7
4.8.1 Let, the difference between const and var
- Let and var are used to declare variables, while const must be initialized and used to declare constants, which refer to the constant value of ordinary types and the memory address of complex types.
- Var has a variable promotion, while let, const, has a “temporary dead band”. If a variable is accessed before it is declared, it will be referred to a ReferenceError instead of using undefined as the default
- Let,const has only block-level scope, while var has only global scope and function scope concepts
4.8.2 Arrow function
- More simplified code syntax
- This is not bound, which means that this cannot be passed using call and apply, and the first argument is the one that needs to be passed
- Arguments, i.e. no arguments to the function, but can use the remaining arguments… The args alternative
function foo(arg1,arg2) {
var f = (. args) = > args[1];
return f(arg1,arg2);
}
foo(1.2); / / 2
Copy the code
- The new keyword cannot be used because the arrow function is not a constructor
- No Prototype attribute
- The yield keyword usually cannot be used in arrow functions (unless nested within an allowed function). Therefore, arrow functions cannot be used as generators.
- If you need to put the object literal back, you can
Var func () = = > ({1} foo:) / / or var func () = = > {return {foo:1}}
Copy the code
4.8.3 Promise
A Promise is simply a container that holds the result of an event (usually an asynchronous operation) that will end in the future.
Promise is a solution to asynchronous programming that makes more sense and is more powerful than traditional solutions — callback functions and events. Clear code structure. Avoid callback hell
Promise has three states, namely, the pending state after initialization, the fulfilled state after resolve, and the Rejected state after rejecte.
Common methods:
Then and catch are actually callback functions that register the success or failure of an asynchronous operation
- Promise.prototype.then() : Can take two arguments, the first a resolve callback and the second a reject callback
- Promise.prototype. Catch () : then(null, rejectFun)
- Promise. Prototype. Finally () [ES8]
- Promise. All (): Only when all become a depressing state, the packaging instance will become a depressing state; If an instance becomes the Rejected state, the wrapper instance becomes the Rejected state.
- Promise.allsettled (): The wrapper instance will end only after all these parameter instances return the result, whether this is a pity or Rejected. This method was introduced by ES2020.
- Promise. Any (): As long as one of the instances becomes a depressing state, the packaging instance will become a depressing state; If all parameter instances become the Rejected state, the wrapper instance becomes the Rejected state. The approach is currently a phase iii proposal.
- Promise.race(): Asynchronous operation race that returns only the fastest one
- Promise.resolve()
- Promise.reject()
- Promise.try(): Synchronous operations can also be performed asynchronously
4.9 Number
4.9.1 Maximum Safe number
Js uses an 8-bit floating number to store numbers, ranging from -2^63 to 2^ 63-1. But it is not correct to add and subtract after a certain value, called the maximum safe value.
The maximum safety value is 2^53-1. The maximum safety value is -2^53+1
The storage structure of Number in js is:
- 1 bit sign bit
- Eleven exponential bits
- Fifty-two mantissa digits
Floating-point numbers are normalized to store numbers. In binary, one digit is reserved before the decimal point, and the normalized value is always 1.***, saving 1 bit. So 52 plus 1 is 53.
You can use third-party libraries such as Bignum, bigInt, etc
4.9.2 Floating point calculation accuracy problem
Because floating-point numbers are stored and computed in binary on the computer, there are precision problems with floating-point numbers such as:
0.1 + 0.2 = 0.30000000000000004
1.0 - 0.9 = 0.09999999999999998
Copy the code
- Round off using toFixed
- Enlarging a number to an integer
- Use a third library such as number-precision for calculations
It’s worth noting
ToFixed is not a full round. Instead, use a fairer banker rounding method. The specific rules are:
Four rounding six into five consideration, five after non zero into a five after zero to see odd even, five before even should be dropped, five before strange to enter a
4.10 Array
4.10.1 Common methods of arrays
Change the original array:
- pop(), push(),shift(),unshift()
- reverse(),sort()
- splice(index, howMany, newAddItem1, newAddItem2, …) . Delete the item
- forEach
Other:
- map, filter, every, some
- find, findIndex
- reduce
- join
4.10.2 Differences between Map and forEach
- Each supports three parameters: item (current item), index (index value), and arR (original array).
- ForEach allows callback to change the elements of the original array, with no return value. Map returns a new array, which behaves as if it were a shallow copy. ForEach, filter, every, some will skip the empty space, map will skip the empty space, but will keep the value.
4.11 Differences between the four For loops
-
Normal for loop
-
ForEach: short for plain for loop, but cannot break the loop
-
for in
- Index to a string
- Out of order (usually used in objects or JSON)
- Extensible attributes are also traversed
- Designed for looping enumerable objects
-
for of
- Object traversal is not supported
- Use of data with obj[symbol.iterator], such as arrays, strings, sets, and maps
4.12JS modular scheme
4.12.1 AMD and CMD
- AMD is produced by the standardization of RequireJS module definition in the process of popularization.
- CMD is the result of the normalization of the module definition by SeaJS during the promotion process.
- For dependent modules, AMD can either delay or advance execution, while CMD delays execution.
- AMD advocates predependency while CMD advocates proximal dependency. (So to speak, CMD is “lazy”)
- AMD supports global require and local require, but CMD does not support global require, so CMD does not have a global API and AMD does.
// AMD relies on the front end
define(['./zty'.'./ty'].function(zty, ty) {
zty.sayName()
ty.sayName()
})
// CMD
define(function(require, exprots, module) {
var zty = require('./zty')
zty.sayName()
// Require only when needed
var ty = require('./ty')
ty.sayName()
})
Copy the code
4.12.1 CommonJs
CommonJS is a modular optimization for servers. The CommonJS module suggests specifying a simple API for declaring modules on the server side, and does not attempt to worry as extensively as AMD does about IO, file systems, conventions, and more. It has the following characteristics:
- It is mainly used in server-side JS, such as Node
- Global object: global
- A file is a module and has a separate scope. All code runs in the module scope and does not pollute the global scope. Modules can be loaded multiple times, but only run once on the first load, and then run results are cached. After loading, the cached results are read directly. (You can expose a timestamp to test this.)
- The order in which the modules are loaded, the order in which the code appears,
- Synchronous loading
- Module. exports: : / / module. Exports: : / / module.exports: : / / module.exports: : / / module
- Exports and module.exports expose the contents of modules
What is the difference between exports and module.exports?
-
Exports within modules: For convenience, Node provides an exports variable for each module that points to module.exports, which adds the following statement to the module header: Var exports = module.exports; / / add methods to module.exports
-
The module.exports method can also return a single data type (String, Number, Object…). Exports can only return an Object Object. All exports objects are ultimately passed through module.exports, so it would be more accurate to say that exports add properties and methods to module.exports.
4.12.2 ES6 Module
ES6 modular specification is ES6 in the language standard level, the realization of module functions, and the implementation is quite simple, its design idea is as far as possible static, make compile time can determine the dependency of the module, as well as input and output variables. And ES6 modules automatically adopt strict mode, whether or not we add “use strict” to the module header.
There are four common commands on the ES6 Module
- Export export
- Export default by default
- Import the import
- Rename the as
Export:
- Export An export should be an interface or understood as a definition, not a value
- Export The exported interface is dynamically bound to its corresponding value, that is, the real-time value inside the module can be obtained through the interface.
- The export command can appear anywhere in the module, as long as it is at the top of the module. If you are in block-level scope, an error is reported, as is the following import command. This is because you can’t do static optimizations when you’re in a conditional block, which goes against the design of the ES6 module.
Export the default:
In essence, export default is to output a variable or method named default on the Module. It is completely different from export, so it cannot be followed by variable declarations, except expressions, functions, and classes.
Import:
- The variables entered by the import command are read-only because it is by nature an input interface. That is, it is not allowed to rewrite interfaces in scripts that load modules.
- Import {interface1} should be used for the interface exported by export
- Import Interface1 should be used for variables exported by Export Default
- The import command is promoted to the top of the module and executed first.
- If the same import statement is repeated multiple times, it is executed once, not multiple times.
4.12.3 CommonJS and ES6 modules
- CommonJS Modules are run time loaded, ES6 Modules are compile-time output interfaces
- CommonJS output is a copy of the value; ES6 Modules output references to values, and changes within the output module can affect the reference changes
- The module path imported by CommonJs can be an expression because it uses the require() method; Es6-modules can only be strings
- CommonJS This points to the current module, ES6 Modules This points to undefined
- ES6 Modules doesn’t have these top-level variables: arguments, require, module, exports, __filename, __dirname
4.12.4 UMD
UMD is designed to allow the same code module to run in projects using CommonJs, CMD, or even AMD. It’s a little “ugly” for compatibility.
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
// AMD
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// Node, CommonJS-like
module.exports = factory(require('jquery'));
} else {
global.returnExports = factory(global.jQuery);
}
}(typeof window! = ="undefined" ? window : this.function( window, noGlobal ) {
// methods. return {... }}))Copy the code
4.13 Shallow and Deep Copies
In simple terms, when copying a complex type, a shallow copy copies the reference address, and a deep copy copies a new property.
How to implement deep copy:
- Copy via JSON
JSON.parse(JSON.stringify())
Copy the code
Although simple, there are some drawbacks:
- Properties on the prototype chain cannot be copied
- Object whose attribute value is a function cannot be copied
- Failed to handle Date correctly and got date.tostring ()
- Failed to properly handle RegExp data and get new Object()
- Will ignore symbol, undefined, symbol
- Object. The assign ({}, target) or {… target}
Advantages:
- JSON cannot be processed or copied.
- Only the top layer can be deeply copied
- Properties on the prototype chain cannot be copied
- Implement a recursive deep copy function
Advantages:
- This solves problems where JSON cannot be processed or copied
- The disadvantages of being able to obtain attributes on the prototype chain are:
- The recursion and logic are complicated
The following is a deep-copy implementation function
function deepClone(obj, hash= new WeakMap()) {// Recursive copyif (obj instanceof RegExp) return new RegExp(obj);
if (obj instanceof Date) return new Date(obj);
if(obj === null || typeof obj ! = ="object") returnobj; // Simple typeif (hash.has(obj)) returnhash.get(obj); // Circular referencelet instance = new obj.constructor();
hash.set(obj, instance);
for (let key in obj) { // no-prototype-builtins
if (obj.hasOwnProperty(key)) {
instance[key] = dc(obj[key], hash)}}return instance
}
Copy the code
4.14 JS application
4.14.1 Main logic for implementing promise. all and promise. race
Promise.prototype.all = function(arr) {
let results = []; // Result array
return new Promise((resolve, reject) = > {
let count = arr.length
for (let i = 0; i < arr.length; i++) {
// The promise return value for arr[I] may be normal
Promise.resolve(arr[i]).then((data) = > {
results[i] = data
--count
if (count <= 0) {
resolve(results)
return
}
}).catch(err= > {
reject(err)
return})}})}Copy the code
Promise.prototype.race = function(promises) {
return new Promise(function(resolve, reject) {
for (var i = 0; i < promises.length; i++) {
Promise.resolve(promises[i]).then(data= > {
resolve(data)
}).catch(err= > {
return reject(err)
})
}
})
}
Copy the code
4.14.2 Anti-shake and Throttling
Anti-shake and throttling are two solutions to problems such as the response not keeping up with the trigger frequency.
- Function shock proof: debounce
- Definition: An event handler executes only once after firing an event more than once, and at the end of the firing operation.
- Function throttle: throttle
- Definition: : after the function event is triggered, it cannot be called continuously within a short time interval. The next function call can only be made after the specified time interval has passed after the last function execution.
- Simple implementation:
function debounce(fn, delay) {
let timer;
return function(. rest) {
timer && clearTimeout(timer)
timer = setTimeout((a)= > fn.apply(this, rest), delay)
}
}
Copy the code
function throttle(fn, delay) {
let start
return function(. rest) {
let now = Date.now() ! start && (start = now)if (now - start >= delay) {
fn.apply(this, rest)
start = now
}
}
}
function throttle2(fn, delay){
let timer
return function(. rest){
if(! timer){ timer = setTimeout((a)= > {
fn.apply(this, rest);
timer = null;
}, delay)
}
}
}
Copy the code
4.14.3 native ajax
- Create an XHR instance
- Open links (request method, URL, synchronous asynchronous)
- Setting request Parameters
- Listen for the onReadyStatechange event
- send
var xhr=new XMLHttpRequest();
xhr.open('POST',url,false);
xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded');
xhr.onreadystatechange=function(){
// readyState == 4 Indicates that the request is complete
if(xhr.readyState==4) {if(xhr.status==200 || xhr.status==304) {console.log(xhr.responseText);
fn.call(xhr.responseText);
}
}
}
xhr.send();
Copy the code
4.14.4 currie
Currying is a technique that converts a function that takes multiple arguments into a function that takes a single argument (the first argument of the original function), and returns a new function that takes the remaining arguments and returns a result.
function curry(fn, ... args) {
return args.length < fn.length ? (.arguments) = >curry(fn, ... args, ... arguments) : fn(... args) }Copy the code
4.14.5 Flattening treatment
- Flattening an array, converting a multilayer array into a one-dimensional array, e.g
[1[2], [[3= > []]]1.2.3]
Copy the code
- The use of Array. Prototype. Flat (the depth). Depth cannot be less than the depth of the array
arr.flat(3)
Copy the code
- traverse
function flat1(arr) {
while(arr.some(item= >Array.isArray(item))) { arr = [].concat(... arr); }return arr;
}
Copy the code
- The recursive implementation
function flat2(arr1) {
return arr1.reduce((acc, val) = > Array.isArray(val) ? acc.concat(flat2(val)) : acc.concat(val), []);
}
Copy the code
- non-recursive
function stackFlatten(input) {
const stack = [...input];
const res = [];
while (stack.length) {
const next = stack.pop();
if (Array.isArray(next)) { stack.push(... next); }else{ res.push(next); }}return res.reverse();
}
Copy the code
- Flattening of objects, containing only ordinary types, arrays, and objects. For example,
{
num: 1.arr: [1.2]
obj: {
name: 'name'}}// After flattening =>
{
num: 1,
arr.[0] :1,
arr.[1] :2,
obj.name: 'name'
}
Copy the code
function _typeof(object) {
let _toString = Object.prototype.toString
return _toString.call(object)
}
function flatten(obj) {
if(! obj)return
let res = {}
function flat(key, value) {
if (_typeof(value) === "[object Array]") {
if (value.length === 0) {
res[key] = []
return
}
for(let k in value) {
flat(key ? `${key}.${k}] ` : k, value[k])
}
} else if (_typeof(value) === "[object Object]") {
if (Object.keys(value).length === 0) {
res[key] = {}
return
}
for(let k in value) {
flat(key ? `${key}.${k}` : k, value[k])
}
} else {
res[key] = value
}
}
flat(' ', obj)
return res
}
Copy the code
4.14.6 Judging that Two Objects are The same
Determine that two objects are the same and that there is no apparent difference between the two objects.
function looseEqual(a, b) {
if (a === b) return true;
const isObjectA = isObject(a);
const isObjectB = isObject(b);
if (isObjectA && isObjectB) {
try {
const isArrayA = Array.isArray(a);
const isArrayB = Array.isArray(b);
if (isArrayA && isArrayB) {
return (
a.length === b.length &&
a.every((e, i) = > {
returnlooseEqual(e, b[i]); })); }else if (a instanceof Date && b instanceof Date) {
return a.getTime() === b.getTime();
} else if(! isArrayA && ! isArrayB) {const keysA = Object.keys(a);
const keysB = Object.keys(b);
return (
keysA.length === keysB.length &&
keysA.every(key= > {
returnlooseEqual(a[key], b[key]); })); }else {
/* istanbul ignore next */
return false; }}catch (e) {
/* istanbul ignore next */
return false; }}else if(! isObjectA && ! isObjectB) {return String(a) === String(b);
} else {
return false; }}Copy the code
The answer comes from the vue source code SRC /shared/util.js
conclusion
I am one of thousands of ordinary front end, I am the first time to write nuggets, if there is a mistake, welcome you correct, grow together. The rest will be included in the next chapter, and the link of the whole Youdao Cloud Note will be shared with you. Thank you for reading!
Do a love to share, love to learn front, I am Andy five, oh yeah!