Source: making a qualified intermediate front-end engineers need to acquire skills | o stars ✨ | give a ❤ ️ attention, ❤ ️ thumb up, ❤ ️ encourages the author
Hello, everyone. I’m Nezha, the demon king. Nice to meet you
Nezha’s Life creed: If you learn something in love will have a strong motivation support.
Learn programming every day, so that you can update a step from your dream, thank you for every programmer who loves programming, no matter how strange the knowledge is, together with me, let the wandering heart settle down, go all the way, come on, 2021 come on! Welcome to follow and add me vx: Xiaoda0423, welcome to like, collect and comment
Don’t be afraid to dream, but don’t just dream. Be a doer, not a talker.
preface
If this post helped you, follow it at ❤️, like it at ❤️, and encourage the author at ❤️. Are you ready for the challenge? Article public number debut, attention programmer Doraemon first time to obtain the latest article
❤ ️ cartridge ❤ ️ ~
Have read:
- Let and const in ES6 series
- ES6 series template string
- ES6 series of arrow functions
- The ES6 emulation implements the Symbol type
- ES6 series iterators and for of
- The ES6 simulation implements a Set data structure
- ES6 series WeakMap
- Let’s talk about Promises
- ES6 complete user manual
- DefineProperty and Proxy in ES6 series
- ES6 series module loading scheme
- ES6 family of private variable implementation
- Front end, school recruit, face taobao, guide
- Front end, social recruit, face taobao, guide
- You work your butt off doing business, you’re not doing very well, and that’s as far as I can help you…
- Tao department front – end campus recruitment person in charge of live transcript
- | his letter to 2021 session of the front-end classmate is self-motivated, can issue in the future!
- Don’t panic when asked about your project experience. Follow this step to give an amazing answer
- Project doesn’t know how to do performance tuning? Try code splitting
HTML module
HTML tags contain special “elements” such as:
<head>, <title>, <body>, <header>, <footer>, <article>, <section>, <p>, <div>, <span>, <img>, <aside>, <audio>, <canvas>, <datalist>, <embed>, <nav>, <output>, <progress>, <video>Copy the code
The article element
Represents a standalone structure in a document, page, application, or website that is intended to be independently assignable or reusable, as in a publication, whether it is a forum post, a magazine or news article, a blog, a user-submitted comment, an interactive component, or other standalone content item.
Section element
Represents a separate part contained within an HTML document that has no more specific semantic elements to represent it, typically including a header.
Value element
Represents a part that has little to do with the rest of the page’s content, is considered a separate part of the content and can be separated separately without affecting the whole.
Audio element
Used to embed audio content in a document.
<audio
controls
src="/zzz.mp3">
dada
<code>audio</code> .
</audio>
Copy the code
The canvas element
Use JavaScript (Canvas API or WebGL API) to draw graphics and graphics animation.
<canvas id="canvas" width="300" height="300"></canvas>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'green';
ctx.fillRect(10, 10, 100, 100);
Copy the code
Datalist element
Contains a set of
<input list="browsers" name="myBrowser" /></label>
<datalist id="browsers">
<option value="Chrome">
<option value="Firefox">
<option value="Internet Explorer">
<option value="Opera">
<option value="Safari">
</datalist>
Copy the code
The details element
You can create a widget that displays the contained information only when switched to the expanded state. The
<details>
<summary>System Requirements</summary>
<p>Requires a computer running an operating system. The computer
must have some memory and ideally some kind of long-term storage.
An input device as well as some form of output device is
recommended.</p>
</details>
Copy the code
System Requirements
Requires a computer running an operating system. The computer must have some memory and ideally some kind of long-term storage. An input device as well as some form of output device is recommended.
Embed element
External content embedded elements
Progress element
Used to show the progress of a task
<progress id="file" max="100" value="70"> 70% </progress>
Copy the code
The output label
Represents the result of a calculation or user action.
The nav element
Represents a portion of a page that is intended to provide navigation links in the current document or other documents
Form widgets:
<form action="/my-handling-form-page" method="post"> <div> <label for="name">Name:</label> <input type="text" id="name"> </div> <div> <label for="mail">E-mail:</label> <input type="email" id="mail"> </div> <div> <label for="msg">Message:</label> <textarea id="msg"></textarea> </div> </form>Copy the code
A single line text box
<input type="text" id="comment" name="comment" value="I'm a text field">
Copy the code
E-mail address field
<input type="email" id="email" name="email" multiple>
Copy the code
The password
<input type="password" id="pwd" name="pwd">
Copy the code
The search box
<input type="search" id="search" name="search">
Copy the code
Telephone number column:
<input type="tel" id="tel" name="tel">
Copy the code
The URL bar:
<input type="url" id="url" name="url">
Copy the code
Multi-line text box:
<textarea cols="30" rows="10"></textarea>
Copy the code
Check box:
<input type="checkbox" checked id="carrots" name="carrots" value="carrots">
Copy the code
Radio button:
<input type="radio" checked id="soup" name="meal">
Copy the code
The Numbers:
<input type="number" name="age" id="age" min="1" max="10" step="2">
Copy the code
The slider:
<input type="range" name="beans" id="beans" min="0" max="500" step="10">
Copy the code
Date and time selector:
<input type="datetime-local" name="datetime" id="datetime">
<input type="month" name="month" id="month">
<input type="time" name="time" id="time">
<input type="week" name="week" id="week">
Copy the code
Color:
<input type="color" name="color" id="color">
Copy the code
File selector:
<input type="file" name="file" id="file" accept="image/*" multiple>
Copy the code
Hidden content:
<input type="hidden" id="timestamp" name="timestamp" value="6354561">
Copy the code
Sending form Data
Client/server architecture
A client (usually a Web browser) sends a request to a server (in most cases Apache, Nginx, IIS, Tomcat, etc.) using the HTTP protocol.
On the client side: Defines how to send data:
Action attribute – This attribute defines where to send data.
Method attribute – This attribute defines how data is sent.
What is form data validation?
Visit any site with a sign-up form and you’ll find that the sign-up page will give you feedback when you submit a form that doesn’t enter the information in the expected format.
- “This field is required” (this field cannot be left blank)
- Please enter your telephone number
- Please enter a valid email address
Use regular expression validation
Example:
A - Matches a character a(does not match b, aa, etc.) ABC - matches a, followed by b, finally, c. a * - match zero or more characters a (+ represent at least match one or more). [^ a] - match one character at a time, but it can't be a. a | b - match one character a or b. [ABC] - match one character at a time, It can be a,b, or C. [^ ABC] -- matches a character, But it can't be a,b, or C. [a-z] -- matches characters in the range a-z and all lowercase (you can use [a-za-z] to cover case, A {5} - Matches character A five times. A {5,7} - matches character A five to seven times, no more or less.Copy the code
AJAX technology mainly relies on the XMLHttpRequest (XHR) DOM object. It can construct HTTP requests, send them, and retrieve the results of the requests.
Form data (Application/X-wwW-form-urlencoded) is composed of a list of urL-encoded key/value pairs. To transmit binary data, HTTP requests are reintegrated into multipart/form-data form.
Build the XMLHttpRequest: XMLHttpRequest is the safest and most reliable way of HTTP requests.
Example:
function sendData(data) { var XHR = new XMLHttpRequest(); var urlEncodedData = ""; var urlEncodedDataPairs = []; var name; // Convert the data object to a URL-encoded array of key/value pairs. for(name in data) { urlEncodedDataPairs.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name])); } // Merge the pairs into a single string and replace all % encoded Spaces with // "+" characters; Matches the behavior of the browser form submission. urlEncodedData = urlEncodedDataPairs.join('&').replace(/%20/g, '+'); Xhr.addeventlistener ('load', function(event) {alert(' yup! The data is sent and the response is loaded. '); }); Xhr.addeventlistener ('error', function(event) {alert(' Oops! Something's wrong. '); }); / / set up our request XHR. Open (' POST ', 'https://example.com/cors.php'); // Add HTTP header xhr. setRequestHeader(' content-type ', 'application/x-www-form-urlencoded'); // Finally, send our data. XHR.send(urlEncodedData); }Copy the code
The FormData object is used to process FormData requests.
Example:
function sendData(data) { var XHR = new XMLHttpRequest(); var FD = new FormData(); // Add our data to the FormData object for(name in data) {fd.append (name, data[name]); } xhr.addeventListener ('load', function(event) {alert('Yeah! The data is sent and the response is loaded. '); }); Xhr.addeventlistener ('error', function(event) {alert('Oops! Make a mistake. '); }); / / set the XHR request address and method. The open (' POST ', 'https://example.com/cors.php'); // Send the formData object. The HTTP request header is automatically set to xhr.send (FD); }Copy the code
Use FormData bound to the form element
<form id="myForm"> <label for="myName"> </form> < form id=" name" name="name" value="John">Copy the code
Example:
window.addEventListener("load", function () { function sendData() { var XHR = new XMLHttpRequest(); // We bind the FormData to the form element. var FD = new FormData(form); // We define what happens when the data is successfully sent. XHR.addEventListener("load", function(event) { alert(event.target.responseText); }); Xhr.addeventlistener ("error", function(event) {alert(' Oops! Something has gone wrong. '); }); / / we set up our request XHR. Open (" POST ", "https://example.com/cors.php"); // The data sent is provided by the user in the form xhr.send (FD); Var form = document.getelementById ("myForm"); / /... Form.addeventlistener ("submit", function (event) {event. PreventDefault (); sendData(); }); });Copy the code
CORS handles cross-domain images
By combining the Crossorigin attribute with the appropriate CORS header, an image defined in the element can be loaded from an external source and used in the
Images with CORS enabled
Although images from other sources can be used in < Canvas > without CORS, this contaminates the canvas and is no longer considered safe, which may raise an exception during the retrieval of data by < Canvas >.
Call the following methods on the “contaminated” canvas:
- in
<canvas>
Is called in contextgetImageData()
-
- in
<canvas>
On the calltoBlob()
- in
- in
<canvas>
On the calltoDataURL()
CORS set properties
Some HTML elements that provide support for CORS, such as or
CanvasRenderingContext2D.getImageData()
CanvasRenderingContext2D. GetImageData () returns a ImageData object, used to describe the canvas area implied pixel data, this area through the rectangles represent, the starting point for sw for (sx, sy), wide, high for sh.
grammar
ImageData ctx.getImageData(sx, sy, sw, sh); Sx The upper-left x-coordinate of the rectangular area of the image data to be extracted. Sy The upper-left y coordinate of the rectangular area of the image data to be extracted. Sw The width of the rectangular area of the image data to be extracted. Sh The height of the rectangular area of the image data to be extracted. Return an ImageData object containing the rectangular ImageData given to the canvas.Copy the code
Use the getImageData method:
<canvas id="canvas"></canvas> var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); ctx.rect(10, 10, 100, 100); ctx.fill(); console.log(ctx.getImageData(50, 50, 100, 100)); // Uint8ClampedArray {width: 100, height: 100, data: Uint8ClampedArray[40000]}Copy the code
HTMLCanvasElement.toBlob()
The htmlCanvasElement.toblob () method creates a Blob object that displays images on the Canvas. The image file can be cached or saved locally, at the discretion of the user agent. If not specified, the default image type is Image/PNG and the resolution is 96dpi.
grammar
canvas.toBlob(callback, type, encoderOptions); Callback to get a single Blob object parameter. Type Specifies the image format. The default format is image/ PNG. This parameter is optional. EncoderOptions Specifies the image quality when the image format is image/ JPEG or image/webp. The Number type is optional. The value is between 0 and 1. If the value of this parameter is not within the specified type and range, the default value is used and the rest of the parameters are ignored. Returned value None.Copy the code
HTMLCanvasElement.toDataURL()
HTMLCanvasElement. ToDataURL () method returns a data URI contains pictures show. You can use the type parameter, which defaults to PNG. The resolution of the image is 96dpi.
- If the height or width of the canvas is zero, then the string is returned.
data:,
“. - If the type passed is not”
image/png
“, but returns the value as"Data: image/PNG"
The type passed in is not supported. - Chrome support”
image/webp
“Type.
grammar
canvas.toDataURL(type, encoderOptions); Type Optional image format. The default is Image/PNG. EncoderOptions Optional If the image format is image/ JPEG or Image /webp, you can select the image quality from 0 to 1. If the value is out of range, the default value 0.92 will be used. Other parameters are ignored. The return value is a DOMString containing the data URI.Copy the code
Example:
<canvas id="canvas" width="5" height="5"></canvas> var canvas = document.getElementById("canvas"); var dataURL = canvas.toDataURL(); console.log(dataURL); // "data:image/png; base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNby // blAAAADElEQVQImWNgoBMAAABpAAFEI8ARAAAAAElFTkSuQmCC"Copy the code
Set image quality:
Var fullQuality = Canvas. ToDataURL ("image/jpeg", 1.0); // data:image/jpeg; base64,/9j/4AAQSkZJRgABAQ... 9 oadambaairaxeapwd/AD / 6 ap/Z "var mediumQuality = canvas. ToDataURL (" image/jpeg", 0.5); Var lowQuality = Canvas. ToDataURL ("image/jpeg", 0.1);Copy the code
Allows browsers to allow cross-domain access requests when downloading image data
Download begins when the user clicks the “Download” button:
function startDownload() {
let imageURL = "https://xxxx";
downloadedImg = new Image;
downloadedImg.crossOrigin = "Anonymous";
downloadedImg.addEventListener("load", imageReceived, false);
downloadedImg.src = imageURL;
}
Copy the code
Canvas’s toDataURL() method is used to convert an image into a PNG image in the form of data:// URL
Preload content with rel=”preload”
The most common use of the tag is to load CSS files that decorate your page:
<link rel="stylesheet" href="styles/main.css">
<link rel="preload" href="style.css" as="style">
<link rel="preload" href="main.js" as="script">
Copy the code
What types of content can be preloaded?
Audio: Audio files. Document: An HTML document to be embedded inside a <frame> or <iframe>. Embed: A resource that will be embedded inside the <embed> element. Fetch: Resources that will be fetched via FETCH and XHR requests, such as an ArrayBuffer or JSON file. Font: font file. Image: image file. Object: a file that will be embedded within the <embed> element. Script: indicates a JavaScript file. Style: Track: WebVTT file. Worker: a JavaScript Web worker or shared worker. Video: Video file.Copy the code
How to make HTML pages that load quickly
- Reduce the page size.
- Minimize file count: Reducing the number of files referenced by a page reduces the number of HTTP requests required to download a page, thus reducing the time to send and receive those requests.
- Use the CDN.
- Reduced domain name lookup: Each individual domain name consumes DNS lookup time, and page load time increases with the number of individual domain names, CSS links, JavaScript, and image resources.
- Cache reused content: Ensure that any content can be cached and has a reasonable expiration date.
- Arrange page components efficiently.
- Reduce the number of inline scripts.
Add vector graphics to web pages
Example:
<! DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Vector versus raster</title> </head> <body> <h1>Vector versus raster</h1> <img src="star.png" alt="A raster star"> <img src="star.svg" alt="A vector star"> </body> </html>Copy the code
Create a circle and a rectangle:
The < SVG version = "1.1" baseProfile = "full" width = "300" height = "200" XMLNS = "http://www.w3.org/2000/svg" > < the rect width = "100%" height="100%" fill="black" /> <circle cx="150" cy="100" r="90" fill="blue" /> </svg>Copy the code
Example:
<img
src="equilateral.svg"
alt="triangle with all three sides equal"
height="87px"
width="100px" />
Copy the code
<svg width="300" height="200">
<rect width="100%" height="100%" fill="green" />
</svg>
Copy the code
Using SVG:
<svg width="100%" height="100%"> <rect width="100%" height="100%" fill="red" /> <circle cx="100%" cy="100%" r="150" Fill ="blue" stroke="black" /> <polygon points="120,0 240,225,225" fill="green"/> <text x="50" y="100" font-family="Verdana" font-size="55" fill="white" stroke="black" stroke-width="2"> Hello! </text> </svg>Copy the code
CSS module
Margin overlap
The margin-top and margin-bottom margins of a block are sometimes merged (collapsed) into a single margin with the size of the maximum of the single margin (or only one of them if they are equal), a behavior called margin folding.
Layout and contain blocks
Cascading context
Elements that satisfy any of the following conditions are formed:
- The document root element (
<html>
); position
A value ofabsolute
(absolute positioning) orrelative
(relative positioning) andz-index
Values are not forauto
The element;position
A value offixed
(fixed position) orsticky
(Sticky location) elements (sticky location works on all browsers on mobile devices, but older desktop browsers don’t support it);- flex (
flexbox
), andz-index
The value is not auto; - grid (
grid
), andz-index
The value is not auto; opacity
Elements whose attribute value is less than 1
Block formatting context
The Block Formatting Context (BFC) is part of the visual CSS rendering of a Web page. It is where the layout of a Block box takes place, and where floating elements interact with other elements.
Block formatting context is created:
- The root element (
<html>
) - Floating elements (elements
float
notnone
) - Absolute positioning elements (
The position of the element is absolute or fixed
) - Inline block elements (elements
The display of the inline - block
) - Table cells (elements
The display for the table cell
, HTML table cells default to this value) - Table title (element
The display for the table caption
, the HTML table title defaults to this value) contain
A value ofLayout, Content, or Paint
The elements of the- Elastic elements (
Display is either flex or inline-flex
Direct child of the element) - Grid elements (
Display is either grid or inline-grid
Direct child of the element)
The use of overflow: auto
To create a BFC that will contain this float, it is common to set the parent overflow: auto or some other non-default overflow: visible value.
Set overflow: auto to create a new BFC to contain the float. Our
CSS elastic box layout
This property is short for the following CSS properties:
flex-grow
flex-shrink
flex-basis
The Flex-shrink attribute specifies the shrink rule for flex elements. Flex elements are shrunk only if the sum of their default widths is greater than the container, based on flex-shrink values.
flex-shrink: 2; The flex - the shrink: 0.6; /* Global values */ flex-shrink: inherit; flex-shrink: initial; flex-shrink: unsetCopy the code
Flex-grow sets the Flex growth factor for the main size of a Flex item. It specifies how much of the remaining space in the Flex container should be allocated to the project (flex growth factor).
The main size is the width or height of the item, depending on the flex-direction value.
Flex-basis specifies the initial size of the Flex element in the main axis direction. This property determines the size of the Flex element’s content-box if you do not use box-sizing to change the box model.
Flex-wrap specifies whether flex elements are displayed in a single line or multiple lines. If newlines are allowed, this property allows you to control the direction of the line stack.
The order attribute specifies the order in which the scalable items in the elastic container are laid out. The elements are laid out in ascending order of the values of the order attribute. Elements with the same order attribute value are laid out in the order in which they appear in the source code.
The flex-flow property is short for flex-direction and flex-wrap.
flex-direction: row
flex-wrap: nowrap
Copy the code
Align attribute
The alt-content property sets how the browser allocates space between and around content items along the vertical axis of the elastic box layout and the main axis of the grid layout.
/*align = center */ / align = center */ align = center; /* align-content: start; / / align: end; / / align: end; /* align-content: flex-start; /* align-content: flex end; /* align-content: flex end; /* Place Flex elements from the end point */ /* Default alignment */ align-content: normal; /* align-content: baseline; align-content: first baseline; align-content: last baseline; /* align = center; /* align = center; /* align = right; /* align = right; /* align = right; /* Evenly distribute items into items that have a half size space at both ends */ evenly content: space-evenly; */ align: stretch; */ align: stretch; /* Evenly distributed items stretch 'automatically' - size items to fill containers */ /* Overflow alignment */ align-Content: Safe Center; align-content: unsafe center; /* global property */ align-content: inherit; /* inherit */ align-content: initial; /* initial value */ align-content: unset; /* * */ is not setCopy the code
align-items
Example:
align-items: stretch;
align-items: center;
align-items: start;
align-items: end;
Copy the code
align-self: stretch; The effect is as follows:
align-self: center; The effect is as follows:
align-self: start; The effect is as follows:
align-self: end; The effect is as follows:
The justify – content ✍
justify-content: center; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /* Pack items from the start */ justify-content: end; /* Pack items from the end */ justify-content: flex-start; /* Array-text: justify; / / justify: justify; / / justify: justify; /* Insert text from the end of the line */ justify-content: left; /* Pack items from the left */ justify-content: right; /* Pack items from the right */ justify-content: space-between; /* array-content: space-around; /* array-content: space-around; /* evenly arrange each element and allocate the same space around each element */ even-content: space-evenly; /* intersperse each element with equal spacing */ intersperse: stretch; 'auto'-sized elements are stretched to fit the size of the container */Copy the code
The place-content attribute is short for align-content and justify-content
Animation ✍
- animation-name
- animation-duration
- animation-timing-function
- animation-delay
- animation-iteration-count
- animation-direction
- animation-fill-mode
- animation-play-state
animation: 3s ease-in 1s infinite reverse both running slidein; animation: 3s linear 1s infinite running slidein; animation: 3s linear 1s infinite alternate slidein; animation: .5s linear 1s infinite alternate slidein; @keyframes slidein { from { transform: scaleX(0); } to { transform: scaleX(1); }}Copy the code
animation-name: none
animation-duration: 0s
animation-timing-function: ease
animation-delay: 0s
animation-iteration-count: 1
animation-direction: normal
animation-fill-mode: none
animation-play-state: running
The length of the unit
CSS has two types of length: relative length and absolute length. Absolute length does not depend on any other measure. Absolute measures maintain their length regardless of the environment in which they are applied.
The relative length depends on the environment used, such as the screen resolution of a computer monitor or the size of a font.
Absolute length is defined in actual units such as inches, centimeters, and points.
The unit of length can be divided into relative unit of length and absolute unit of length: relative/absolute
- A unit of relative length. The unit of relative length: the unit of relative font length and the unit of relative visual area length
- Unit of relative font length,
Em and EX, and REM and CH for CSS3
- A unit of relative apparent area length, as
vh, vw, vmin, vmax
- A unit of absolute length
px,pt,cm,mm,pc
Units in CSS:
Time unit s,ms, Angle unit deg,rad, length unit px,em
% is not a unit of length
Selectors: 1, class selector, 2, ID selector, 3, attribute selector, 4, pseudo-class selector, 5, pseudo-element selector.
:first-child
:last-child
::first-line
::first-letter
::before
::after
Copy the code
Relational selector: 1, descendant selector, 2, adjacent descendant selector, 3, sibling selector, 4, adjacent sibling selector.
Rules: @
@rules are rules that start with an @ character, such as @media, @font-face, @Page, and @supportCopy the code
Block-level elements and elements that display as blocks are not the same thing.
✍, clear floating: ✍
.clear:after { content: '', display: table; // Block, list-item clear: both; }Copy the code
Not using list-item is:
- First, it has more characters
- Unwanted bullets will appear
- Internet Explorer does not support pseudo-elements
display
Refers tolist-item
, mainly because of poor compatibility. For Internet Explorer, common element Settingsdisplay:list-item
It works, but:before/:after
Pseudo-elements are not valid.
Block-level boxes are responsible for the structure, and inline boxes are responsible for the content.
A tag element is inline by default. Set display:block to block and width: 100%.
box-sizing
The box-sizing property is used to change the detail of the width function. 4 boxes inside the box:
- content box
- padding box
- border box
- margin box
By default,width is applied to the content box. Box-sizing allows you to change the box that width is applied to into several other boxes.
✍. In theory
.box1 { box-sizing: content-box; }
.box2 { box-sizing: padding-box; }
.box3 { box-sizing: border-box; }
.box4 { box-sizing: margin-box; }
Copy the code
✍
.box1 { box-sizing: content-box; } // The default value. Box2 {box-sizing: padding-box; Box-sizing: border-box; box-sizing: border-box; box-sizing: border-box; } // Support. Box4 {box-sizing: margin-box; } // Never supportedCopy the code
Global reset is not recommended. This tends to create unnecessary consumption, and this approach does not solve all problems.
* Do not use wildcards as much as possible because they select all labeled elements. For normal inline elements, box-sizing has no effect on their rendering performance, regardless of the value. Also, for some elements, the default box-sizing is border-box, so there is no need for consumption.
How the Internet works
What happens when you type an Internet address into your browser:
- Enter the WWW address in your browser
- The browser interacts with the HTTP server at this address
- The HTTP server receives the request from the browser
- The HTTP server finds web documents
- The HTTP server sends Web documents
- The browser receives the document
- Browser processing source code
- Browser displays Web page
The server side calculator contains HTTP server software to process all web page requests. When you type an Internet address into your browser, the browser makes a request that propagates over a long computer network until it finds the address of the remote computer. After the request reaches the HTTP server, the HTTP server analyzes the request, searches the server’s hard disk for the requested page, and responds to the request by returning the desired Web page.
The response travels along another chain of computers until it reaches your computer. The browser then opens the response and reads the content sent back by the HTTP server. If the server sends an HTML document or other document that the browser can parse, the browser reads the document’s source code and processes it into a displayable Web page.
- Stylesheets are made up of rules
- Rules consist of selectors and declarations.
- Declarations consist of attributes and values.
- The value can be a keyword, length, color, string, integer, real, or URL.
- Em metrics are best used for screen layouts.
- Uris are used to include style sheets and background images in CSS.
- You can use the style attribute to include styles inline directly within an HTML element.
The selector
- Class and ID selectors
- Universal selector
- Descendant selector
- Direct sub-selector
- Adjacent selector
- Attribute selector
- Pseudo elements
- pseudo-classes
Selection based on attribute values
The property value selector applies style declarations based on the existence and value of the property.
input[type="text"]{
background: blue;
color: white;
border: 3px solid royalblue;
}
<input type="text" name="first_name" value="name" size="25"/>
Copy the code
Property substring selector
A string that appears within another string is called a string.
a[href^="ftp://"] {
background: blue;
color: white;
border: 3px solid royalblue;
}
<a href="ftp://ftp.example.com"/>dadaqianduan.cn</a>
Copy the code
Pseudo-classes: Pseudo-classes are used to represent dynamic events, state changes, or situations in the document that cannot be easily implemented in other ways, such as a user’s mouseover or click on an element. Pseudo-classes apply styles to the occurrence of a particular state on a target element.
Dynamic pseudo class
:link
, which indicates an unvisited hyperlink:visited
, which indicates the accessed hyperlink:hover
, indicating that the mouse pointer is currently stuck on the element:active
, indicating that the user is clicking on the element
a:link {
color: red;
}
a:visited {
color: yellow;
}
Copy the code
The :first-child structured pseudo-class is used only when one element is the first child of another element.
Text attributes
letter-spacing
Property and how you can use it to increase and decrease the spacing between letters in a wordword-spacing
Property and how you can use it to increase or decrease the spacing between words in a sentencetext-indent
Property and how to use it to control the indentation of text in a paragraphtext-align
Property and how to use it to align text in the documenttext-decoration
Property and how to use it to underline, underline, and strikeout texttext-transform
Property and how to use it to control the case of text and to convert between letter casewhite-space
Property and how to use it to control the flow and formatting of text.
letter-spacing
Property that controls the spacing of letters.
letter-spacing: normal;
Copy the code
word-spacing
Attribute used for spacing between Confucius words
word-spacing: normal;
Copy the code
text-indent
Property to indent paragraph texttext-align
Property-aligned texttext-decoration
Property to underline, underline, and delete text.text-transform
Property to control the case of the text
#capitalize {
text-transform: capitalize;
}
#uppercase {
text-transform: uppercase;
}
#lowercase {
text-transform: lowercase;
}
Copy the code
white-space
Property to allow controlweb
Text formatting of document source code
Font properties
font-family
Property to specify the font.font-style
Property is used to switch between the different styles provided by a particular font.font-weight
The stylesheet properties provide the ability to specify font thickness.font-size
Property is used to control the font size
Overflow content
The OVERFLOW property of CSS is used to handle content that is susceptible to size limits and is likely to overflow the boundaries of size limits. Two of the most common uses of the Overflow property are to hide content when there is more space than is available, or to make redundant content accessible through scrollbars.
overflow: visible | hidden | scroll | auto
Copy the code
Triangle and other graphics drawing
div {
width: 0;
border: 10px solid;
border-color: #f30 transparent transparent;
}
Copy the code
<style type="text/css">
.div5 {
width: 0;
border: 10px solid;
border-color: #f30 transparent transparent;
}
.div1 {
width: 10px;
height: 10px;
border: 10px solid;
border-color: #f30 transparent transparent;
}
.div2 {
width: 10px;
height: 10px;
border: 10px solid;
border-color: #f30 #00f #396 #0f0;
}
.div3 {
width: 0;
border-width: 10px 20px;
border-style: solid;
border-color: #f30 transparent transparent;
}
.div4 {
width: 0;
border-width: 10px 20px;
border-style: solid;
border-color: #f30 #f30 transparent transparent;
}
</style>
Copy the code
A pivotal role in CSS
line-height
Row height is defined as the distance between the two baselinesvertical-align
The default value for is the baseline
JavaScript module
Event example:
const btn = document.querySelector('button');
btn.onclick = function() {
const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
document.body.style.backgroundColor = rndCol;
}
Copy the code
Array
Create an array
var fruits = ['Apple', 'Banana']; console.log(fruits.length); / / 2Copy the code
Access array elements by index
var first = fruits[0];
// Apple
var last = fruits[fruits.length - 1];
// Banana
Copy the code
Through the array
fruits.forEach(function (item, index, array) {
console.log(item, index);
});
// Apple 0
// Banana 1
Copy the code
Adds an element to the end of the array
var newLength = fruits.push('Orange');
// newLength:3; fruits: ["Apple", "Banana", "Orange"]
Copy the code
Remove the element at the end of the array
var last = fruits.pop(); // remove Orange (from the end)
// last: "Orange"; fruits: ["Apple", "Banana"];
Copy the code
Remove the first (header) element of the array
var first = fruits.shift(); // remove Apple from the front
// first: "Apple"; fruits: ["Banana"];
Copy the code
Adds an element to the head of an array
var newLength = fruits.unshift('Strawberry') // add to the front
// ["Strawberry", "Banana"];
Copy the code
Find the index of an element in an array
fruits.push('Mango'); // ["Strawberry", "Banana", "Mango"] var pos = fruits.indexOf('Banana'); / / 1Copy the code
Copy an array
var shallowCopy = fruits.slice(); // this is how to make a copy
// ["Strawberry", "Mango"]
Copy the code
methods
Array.prototype.pop() removes the last element of the Array and returns it.
Array.prototype.push() adds one or more elements to the end of the Array and returns the new length of the Array.
Array.prototype.reverse() Reverses the order of elements in an Array, i.e. the first element becomes the last element, and the last element becomes the first element.
Array.prototype.shift() removes the first element of the Array and returns it.
Array.prototype.sort() sorts the Array elements and returns the current Array.
Array.prototype.splice() adds or removes any element from the Array at any location.
Array.prototype.unshift() adds one or more elements to the beginning of the Array and returns the new length of the Array.
Array.prototype.concat() returns a new Array composed of the current Array and several other arrays or non-array values.
Array.prototype.join() joins all Array elements into a string.
Array.prototype.slice() extracts a segment of the current Array and combines it into a new Array.
Array.prototype.tostring () returns a string composed of all Array elements. Cover the Object on the prototype chain. The prototype. The toString () method.
Array.prototype.indexof () returns the indexOf the first element in the Array equal to the specified value, or -1 if no such element is found.
Array. The prototype. The lastIndexOf () returns an Array of the last (first) from the right number and specify a value equal to the index of the element, if no such element, it returns 1.
Array.prototype.foreach () executes a callback function once forEach element in the Array.
Array.prototype.every() returns true if every element in the Array satisfies the test function, false otherwise.
Array.prototype.some() returns true if at least one element in the Array satisfies the test function, false otherwise.
Array.prototype.filter() puts all the Array elements that return true in the filter function into a new Array and returns it.
Array.prototype.map() returns a new Array of the return values of the callback function.
The array.prototype.reduce () reduce() method executes a reducer function (ascending) that you provide for each element in the Array, summarising the results into a single return value.
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15
Copy the code
Array. The prototype. ReduceRight () reduceRight () method takes a function as accumulator (accumulator) and an Array of each value (from right to left) will reduce it to a single value.
const array1 = [[0, 1], [2, 3], [4, 5]].reduceRight(
(accumulator, currentValue) => accumulator.concat(currentValue)
);
console.log(array1);
// expected output: Array [4, 5, 2, 3, 0, 1]
Copy the code
Boolean
A Boolean object is an object wrapper for Boolean values.
0, -0, NULL, false, NaN, undefined, or an empty string (“”), the object has an initial value of false.
Any object whose value is not undefined or NULL will be evaluated to true when passed to the conditional statement.
var x = new Boolean(false); If (x) {// this code will be executed} var x = false; } var x = Boolean(expression);} var x = Boolean(expression); Var x =! (expression); Var x = new Boolean(expression); / / not so goodCopy the code
Boolean. Prototype. The toString () according to the value of the object returns a string “true” or “false”. Rewrite the Object. The prototype. The toString () method.
Boolean. Prototype. The valueOf () returns to the original value of the Boolean object. Override the object.prototype.valueof () method.
Date Creates a JavaScript Date instance that is rendered at some point in time.
new Date();
new Date(value);
new Date(dateString);
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
Copy the code
The only way to create a new Date object is through the new operator, for example: let now = new Date();
If called as a regular function (that is, without the new operator), it returns a string, not a Date object.
The Date() constructor has four basic forms
Year indicates the integer value of the year. MonthIndex indicates the integer value of a month, from 0 (January) to November (December). Date Indicates the integer value of the day in a month, starting with 1. The default value is 1. Hours Indicates the integer value of the number of hours in a day (in the 24-hour system). The default value is 0 (midnight). Minutes is the integer value of the minute portion of a complete time, such as 01:10:00. The default value is 0. Seconds represents the integer value of the second portion of a complete time, such as 01:10:00. The default value is 0. Milliseconds represents an integer value for the millisecond portion of a complete time. The default value is 0.Copy the code
Instance methods
Date.prototype.getdate () returns the days (1-31) in the month of the specified Date object, based on the local time.
Date.prototype.getday () returns the day of the week (0-6) of the specified Date object based on the local time.
Date. Prototype. GetFullYear () returns the specified Date according to the local time of the year return four-digit year (4 digits).
Date.prototype.gethours () returns the hour of the specified Date object (0-23) based on the local time.
The Date. The prototype. The getMilliseconds () returns the specified Date according to the local time of milliseconds (0-999).
Date. Prototype. GetMinutes () returns the specified Date according to the local time of minutes (0-59).
Date.prototype.getmonth () returns the month (0-11) of the specified Date object based on the local time.
The Date. The prototype. GetSeconds () returns the specified Date according to the local time the number of seconds (0-59).
Date.prototype.gettime () returns the number of milliseconds that have passed since 1970-1-1 00:00:00 UTC, and a negative value for the time before 1970-1-1 00:00:00 UTC.
Function
Function.prototype.apply()
Function.prototype.bind()
Function.prototype.call()
Function.prototype.toString()
Copy the code
JSON
JSON.parse()
JSON.stringify()
Copy the code
Math methods
Math.abs(x) returns the absolute value of a number. Math.acos(x) returns the arc cosine of a number. Math.acosh(x) returns the inverse hyperbolic cosine of a number. Math.asin(x) returns the arc sine of a number. Math.asinh(x) returns the inverse hyperbolic sine of a number. Math.atan(x) returns the inverse tangent of a number. Math.atanh(x) returns the inverse hyperbolic tangent of a number. Math.atan2(y, x) returns the inverse tangent of y/x. Math.cbrt(x) returns the cube root of a number. Math.ceil(x) returns the smallest integer greater than a number, that is, the value rounded up. Math.clz32(x) returns the number of leading zeros of a 32-bit integer. Math.cos(x) returns the cosine of a number. Math.cosh(x) returns the hyperbolic cosine of a number. Math.exp(x) returns the argument power of Euler's constant, Ex, where x is the argument and E is euler's constant (2.718... , the base of the natural log). Math.expm1(x) returns the value exp(x) -1. Math.floor(x) returns the largest integer less than one number, that is, the value of a number rounded down. Math.fround(x) returns the nearest single precision floating-point representation of a number. Math.hypot([x[, y[,...]]]) returns the square root of the sum of squares of all its arguments. Math.imul(x, y) returns the result of a 32-bit integer multiplication. Math.log(x) returns the natural logarithm of a number (㏒e, as ln). Math.log1p(x) returns the natural logarithm of the sum of a number plus one (㏒e, i.e., ln). Math.log10(x) returns a logarithm of base 10. Math.log2(x) returns a logarithm of base 2. Math.max([x[, y[,...]]]) returns zero to the maximum of multiple values. Math.min([x[, y[,...]]]) returns zero to the lowest of multiple values. Math.pow(x, y) returns a number to the y power. Math.random() returns a pseudorandom number between 0 and 1. Math.round(x) returns the rounded integer. Math.sign(x) returns the sign of a number, knowing whether a number is positive, negative, or 0. Math. sine (x) returns the sine of a number. Math.sinh(x) returns the hyperbolic sine of a number. Math.sqrt(x) returns the square root of a number. Math.tan(x) returns the tangent of a number. Math.tanh(x) returns the hyperbolic tangent of a number. Math.tosource () returns the string "Math". Math.trunc(x) returns the integer part of a number, directly excluding the decimal point and the part after it.Copy the code
Number method
Number.isnan () determines whether the value passed isNaN. Number.isfinite () determines the type of value to be passed and whether it is itself finite. Number.isinteger () determines that the value type passed is "Number" and that it is an integer. Number.parsefloat () is the same as the global object parseFloat(). Number.parseint () is the same as the global parseInt().Copy the code
Object
The Object constructor creates an Object wrapper.
Object.assign() creates a new Object by copying one or more objects. Object.create() creates a new Object using the specified stereotype objects and properties. Object.defineproperty () adds a property to the Object and specifies the configuration for that property. Object.defineproperties () adds multiple properties to an Object and specifies their configuration separately. Object.entries() returns an array of [keys, values] of the enumerable properties of the given Object itself. Object.freeze() Freezes objects: Other code cannot delete or change any properties. Object. GetOwnPropertyDescriptor () returns the attribute configuration Object. Object. GetOwnPropertyNames () returns an array, it contains the specified Object all can be enumerated or not enumerated attribute names. Object. GetOwnPropertySymbols () returns an array, it contains the specified Object itself all the symbol attributes. Object.getprototypeof () returns the prototype Object of the specified Object. Object.is() compares two values for the same. Object.isextensible () determines whether an Object isExtensible. Object.isfrozen () determines whether the Object isFrozen. Object.issealed () determines whether the Object isSealed. Object.setprototypeof () sets the Prototype (that is, the internal [[Prototype]] property) of an Object.Copy the code
WeakMap
A WeakMap object is a set of key/value pairs where the keys are weakly referenced. The key must be an object, and the value can be arbitrary.
WeakSet
WeakSet objects allow you to store weakhold objects in a collection.
grammar
new WeakSet([iterable]);
Copy the code
instanceof
The instanceof operator detects whether the constructor’s prototype property is present on the prototype chain of an instance object.
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
const auto = new Car('2323', '2324', 1234);
console.log(auto instanceof Car);
// expected output: true
console.log(auto instanceof Object);
// expected output: true
Copy the code
typeof
The typeof operator returns a string representing the typeof the unevaluated operand.
console.log(typeof 42);
// expected output: "number"
console.log(typeof 'blubber');
// expected output: "string"
console.log(typeof true);
// expected output: "boolean"
console.log(typeof undeclaredVariable);
// expected output: "undefined"
Copy the code
new
The new operator creates an instance of a user-defined object type or an instance of a built-in object with a constructor.
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
const car1 = new Car('sdfs', 'sdfsd sdf', 2234);
console.log(car1.make);
// expected output: "Eagle"
Copy the code
Promises/A + specification
- Fulfill is a sequence of actions that occur when a promise succeeds, such as state change, callback execution. Although the specification uses the word fulfill, promise implementations are often referred to as resolve.
- Reject, a series of operations that are performed when a promise fails
- Eventual value, the eventual value, is what is passed to the solution callback when the promise is resolved. Because promises are disposable, the eventual value, sometimes called the value, marks the end of the promise wait state.
- Reason, the reason for rejection, is the value passed to the rejection callback when a Promise is rejected.
Example:
var fs = require('fs')
function writeFileAsync(fpath, data, cb) {
fs.writeFile(fpath, data, function(err) {
cb(err);
});
}
var fs = require('fs')
var Promise = require('bluebird');
function writeFileAsync(fpath, data) {
return new Promise(function(resolve, reject) {
fs.writeFile(fpath, data, function(err){
if(err) reject(err)
else resolve()
})
})
}
Copy the code
// 回调嵌套
request(url, funcion(err, res, body) {
if(err) handleError(err)
fs.writeFile('1.txt', body, function(err) {
if(err) handleError(err)
request(url2, function(err, res, body) {
if(err) handleError(err)
})
})
})
// Promise写法
request(url)
.then(function(result) {
return wirteFileAsync('1.txt', result)
})
.then(function(result) {
return request(url2)
})
.catch(function(e){
handleError(e)
})
Copy the code
Traffic light problem
function red() { console.log('red'); } function green() { console.log('green'); } function yellow() { console.log('yellow'); } var tic = function(timer, cb) { return new Promise(function(resolve, reject) { setTimeout(function(){ cb(); resolve(); },timer); }; }; var d = new Promise(function(resolve, reject){resolve(); }); var step = function(def) { def.then(function() { return tic(3000, red); }).then(function() { return tic(2000, green); }).then(function() { return tic(1000, yellow); }); } var d = new Promise(function(resolve, reject) {resolve(); }); var step = function(def){ while(true) { def.then(function() { return tic(3000, red); }).then(function() { return tic(2000, green); }).then(function() { return tic(1000, yellow); }); } } var d = new Promise(function(resolve, reject) { resolve(); }); var step = function(def) { def.then(function() { return tic(3000, red); }).then(function() { return tic(2000, green); }).then(function() { step(def); }); }Copy the code
Optimization:
var tic = function(timmer, str){
return new Promise(function(resolve, reject) {
setTimeout(function() {
console.log(str);
resolve(1);
}, timmer);
});
};
function *gen(){
yield tic(3000, 'red');
yield tic(1000, 'green');
yield tic(2000, 'yellow');
}
var iterator = gen();
var step = function(gen, iterator){
var s = iterator.next();
if (s.done) {
step(gen, gen());
} else {
s.value.then(function() {
step(gen, iterator);
});
}
}
step(gen, iterator);
Copy the code
var promise = new Promise(function(resolve) {
resolve(42);
});
promise.then(function(value) {
console.log(value);
}).catch(function(error) {
console.log(error);
});
Copy the code
Asynchronous processing of callback functions is used
GetAsync ("file.txt", function(error, result) {if(error){// Throw error; } // Handle when success is achieved});Copy the code
An example of using promises for asynchronous processing
var promise = getAsyncPromise('fileA.txt'); Then (function(result) {// obtain the file content successfully}).catch(function(error) {// obtain the file content failed});Copy the code
Constructor
Promise is similar to XMLHttpRequest in that it creates a new Promise object from the Promise constructor as an interface.
To create a Promise object, instantiate it by calling the promise constructor using new.
Var promise = new Promise(function(resolve, reject) {// Call resolve, reject});Copy the code
promise.then(onFulfilled, onRejected)
Copy the code
OnFulfilled will be called on resolve(success)
OnRejected is called when reject(fail)
The state of the Promise
A Promise object instantiated with new Promise has three states.
This is very depressing. This is very depressing. This will be called onFulfilled
"has-rejection" - Rejected
reject
(失败)时。此时会调用 onRejected
“Unresolved” -pending is neither a resolve nor reject state. The initial state of the promise object after it was created
The state of the promise object will never change again after the transition from Pending to Fulfilled or Rejected.
That is, unlike, say, an Event, a Promise function executed after a.then can be guaranteed to be called only once.
Create a PROMISE object for XHR
function getURL(URL) { return new Promise(function (resolve, reject) { var req = new XMLHttpRequest(); req.open('GET', URL, true); req.onload = function() { if(req.status === 200) { resolve(req.responseText); }else{ reject(new Error(req.statusText)); }}; req.onerror = function() { reject(new Error(req.statusText)); }; req.send(); }); } // Run the example XXX var URL = "http://x'x'x.org/get"; getURL(URL).then(function onFulfilled(value){ console.log(value); }).catch(function onRejected(error){ console.error(error); });Copy the code
Promise.resolve(42).then(function(value){
console.log(value);
});
Copy the code
var promise = new Promise(function (resolve){
console.log("inner promise"); // 1
resolve(42);
});
promise.then(function(value){
console.log(value); // 3
});
console.log("outer promise"); // 2
nner promise // 1
outer promise // 2
42 // 3
Copy the code
Example:
function taskA() {
console.log("Task A");
}
function taskB() {
console.log("Task B");
}
function onRejected(error) {
console.log("Catch Error: A or B", error);
}
function finalTask() {
console.log("Final Task");
}
var promise = Promise.resolve();
promise
.then(taskA)
.then(taskB)
.catch(onRejected)
.then(finalTask);
Task A
Task B
Final Task
Copy the code
Differences between AMD and CMD
- CMD advocates dependency near, AMD advocates dependency front.
- AMD is pre-execution, CMD is delayed execution
AMD and CMD both use the module specification for the browser side, while on the server side, such as Node, the CommonJS specification is used.
The CommonJS specification loads modules synchronously, that is, only after the load is complete can the following operations be performed.
The AMD specification loads modules asynchronously, allowing you to specify callback functions.
- The CommonJS module outputs a copy of the value, and the ES6 module outputs a reference to the value.
- The CommonJS module is a runtime load, and the ES6 module is a compile-time output interface.
CommonJS loads an object (the module.exports property) that will only be generated after the script has run. While an ES6 module is not an object, its external interface is just a static definition, which is generated during the static code parsing phase.
The CommonJS module outputs a copy of the value, which means that once a value is printed, changes within the module cannot affect it.
How do I view code utilization
- Open Chrome Dev Tool;
- Press Cmd + Shift + P or Ctrl + Shift + P;
- Enter Coverage and select the first option that appears;
Use array.includes to process multiple conditions
Example:
function test(fruit) { if (fruit == 'apple' || fruit == 'strawberry') { console.log('red'); }}Copy the code
Optimization:
Function test(fruit) {// const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; if (redFruits.includes(fruit)) { console.log('red'); }}Copy the code
Reduce nesting and advance return statements
function test(fruit, quantity) { const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; If (fruit) {// If (fruit) {// if (redfruits.includes (fruit)) {console.log('red'); // Condition 3: quantity must be greater than 10 if (quantity > 10) {console.log('big Quantity '); } } } else { throw new Error('No fruit! '); }} // Test (null); // Throw error: No fruits test('apple'); // Print: red test('apple', 20); // Print: red, big quantityCopy the code
Optimization:
Function test(fruit, quantity) {const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; // Condition 1: throw an error early if (! fruit) throw new Error('No fruit! '); If (redfruits.includes (fruit)) {console.log('red'); // Condition 3: quantity must be greater than 10 if (quantity > 10) {console.log('big Quantity '); }}}Copy the code
Optimization:
Function test(fruit, quantity) {const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; if (! fruit) throw new Error('No fruit! '); // Condition 1: throw an error early if (! redFruits.includes(fruit)) return; // Condition 2: Return console.log('red') in advance when fruit is not red; If (quantity > 10) {console.log('big Quantity '); }}Copy the code
Use the function’s default arguments and destruct
Always check for null/undefined values and assign default values when using JavaScript:
function test(fruit, quantity) { if (! fruit) return; const q = quantity || 1; // If the quantity parameter is not provided, the default is 1 console.log(' We have ${q} ${fruit}! `); } // Test ('banana'); // We have 1 banana! test('apple', 2); // We have 2 apple!Copy the code
Optimization:
Function test(fruit, quantity = 1) {// I default to 1 if no quantity parameter is provided. fruit) return; console.log(`We have ${quantity} ${fruit}! `); } // Test ('banana'); // We have 1 banana! test('apple', 2); // We have 2 apple!Copy the code
Function test(fruit) {// Print fruit. Name if (fruit && fruit. Name) {console.log (fruit. Name); } else { console.log('unknown'); }} // Test (undefined); // unknown test({ }); // unknown test({ name: 'apple', color: 'red' }); // appleCopy the code
Optimization:
Deconstruction - get the name attribute only / / / / the default parameters assigned an empty object {} function test ({name} = {} {the console. The log (name | | 'unknown'); } // Test (undefined); // unknown test({ }); // unknown test({ name: 'apple', color: 'red' }); // appleCopy the code
Optimization:
_.get() function test(fruit) {console.log(_.get(fruit, 'name', 'unknown'); } // The test result is test(undefined); // unknown test({ }); // unknown test({ name: 'apple', color: 'red' }); // appleCopy the code
Select the Map/Object literal instead of the Switch statement
Example:
Function test(color) {switch (color) {case 'red': return ['apple', 'strawberry']; case 'yellow': return ['banana', 'pineapple']; case 'purple': return ['grape', 'plum']; default: return []; }} // Test (null); // [] test('yellow'); // ['banana', 'pineapple']Copy the code
Optimization:
Const fruitColor = {red: ['apple', 'strawberry'], yellow: ['banana', 'Strawberry '], Purple: ['grape', 'plum'] }; function test(color) { return fruitColor[color] || []; }Copy the code
// Use Map, FruitColor = new Map().set('red', ['apple', 'strawberry']).set('yellow', ['banana']).set(' strawberry', ['banana'], 'pineapple']) .set('purple', ['grape', 'plum']); function test(color) { return fruitColor.get(color) || []; }Copy the code
const fruits = [ { name: 'apple', color: 'red' }, { name: 'strawberry', color: 'red' }, { name: 'banana', color: 'yellow' }, { name: 'pineapple', color: 'yellow' }, { name: 'grape', color: 'purple' }, { name: 'plum', color: 'purple' } ]; Function test(color) {return fruits.filter(f => f.color == color); }Copy the code
Every and Array. Some are used to handle all/some conditions
const fruits = [ { name: 'apple', color: 'red' }, { name: 'banana', color: 'yellow' }, { name: 'grape', color: 'purple' } ]; function test() { let isAllRed = true; For (let f of fruits) {if (! isAllRed) break; isAllRed = (f.color == 'red'); } console.log(isAllRed); // false }Copy the code
Optimization:
const fruits = [ { name: 'apple', color: 'red' }, { name: 'banana', color: 'yellow' }, { name: 'grape', color: 'purple' } ]; Function test() {const isAllRed = fruit.every (f => f.color == 'red'); console.log(isAllRed); // false }Copy the code
The use of Array. Some
const fruits = [ { name: 'apple', color: 'red' }, { name: 'banana', color: 'yellow' }, { name: 'grape', color: 'purple' } ]; Function test() {const isAnyRed = fruit. some(f => f.color == 'red'); console.log(isAnyRed); // true }Copy the code
Spread operator
Example:
const favoriteFood = ['Pizza', 'Fries', 'Swedish-meatballs']; console.log(... favoriteFood); //Pizza Fries Swedish-meatballsCopy the code
The for… Of the iterator
const toolBox = ['Hammer', 'Screwdriver', 'Ruler']
for(const item of toolBox) {
console.log(item)
}
// Hammer
// Screwdriver
// Ruler
Copy the code
Includes () method
const garge = ['BMW', 'AUDI', 'VOLVO'];
const findCar = garge.includes('BMW');
console.log(findCar);
// true
Copy the code
Empty or truncate an array
const arr = [11, 22, 33, 44, 55, 66];
// truncanting
arr.length = 3;
console.log(arr); //=> [11, 22, 33]
// clearing
arr.length = 0;
console.log(arr); //=> []
console.log(arr[2]); //=> undefined
Copy the code
Simulate named parameters using object destructuring
Example:
doSomething({ foo: 'Hello', bar: 'Hey! ', baz: 42 }); function doSomething(config) { const foo = config.foo ! == undefined ? config.foo : 'Hi'; const bar = config.bar ! == undefined ? config.bar : 'Yo! '; const baz = config.baz ! == undefined ? config.baz : 13; / /... }Copy the code
Optimization:
function doSomething({ foo = 'Hi', bar = 'Yo! ', baz = 13 } = {}) { // ... }Copy the code
Use async/await to await multiple Async functions
await Promise.all([anAsyncCall(), thisIsAlsoAsync(), oneMore()])
Copy the code
Create a pure object
Example:
const pureObject = Object.create(null);
console.log(pureObject); //=> {}
console.log(pureObject.constructor); //=> undefined
console.log(pureObject.toString); //=> undefined
console.log(pureObject.hasOwnProperty); //=> undefined
Copy the code
Tiled multidimensional arrays
Example:
Const arr = [11, [22, 33], [44, 55], 66]; const flatArr = [].concat(... arr); //=> [11, 22, 33, 44, 55, 66]Copy the code
Optimization:
unction flattenArray(arr) { const flattened = [].concat(... arr); return flattened.some(item => Array.isArray(item)) ? flattenArray(flattened) : flattened; } const arr = [11, [22, 33], [44, [55, 66, [77, [88]], 99]]]; const flatArr = flattenArray(arr); //=> [11, 22, 33, 44, 55, 66, 77, 88, 99]Copy the code
Array.prototype
The array. prototype property represents the prototype of the Array constructor and allows you to add new properties and methods to all Array objects.
Example:
/* If the JavaScript itself does not provide the first() method, add a new method that returns the first element of the array. */ if(! Array.prototype.first) {array.prototype. first = function() {console.log(' if the JavaScript itself does not provide the first() method, Adds a new method that returns the first element of an array. `); return this[0]; }}Copy the code
Array.isArray(Array.prototype);
// true
Copy the code
Methods – methods that change themselves
Array.prototype.pop() removes the last element of the Array and returns it. Array.prototype.push() adds one or more elements to the end of the Array and returns the new length of the Array. Array.prototype.reverse() Reverses the order of elements in an Array, i.e. the first element becomes the last element, and the last element becomes the first element. Array.prototype.shift() removes the first element of the Array and returns it. Array.prototype.sort() sorts the Array elements and returns the current Array. Array.prototype.splice() adds or removes any element from the Array at any location. Array.prototype.unshift() adds one or more elements to the beginning of the Array and returns the new length of the Array.Copy the code
They don’t change their methods
Array.prototype.concat() returns a new Array composed of the current Array and several other arrays or non-array values. Array.prototype.join() joins all Array elements into a string. Array.prototype.slice() extracts a segment of the current Array and combines it into a new Array. Array.prototype.tostring () returns a string composed of all Array elements. Cover the Object on the prototype chain. The prototype. The toString () method. Array.prototype.indexof () returns the indexOf the first element in the Array equal to the specified value, or -1 if no such element is found. Array. The prototype. The lastIndexOf () returns an Array of the last (first) from the right number and specify a value equal to the index of the element, if no such element, it returns 1.Copy the code
Traversal methods
Array.prototype.foreach () executes a callback function once forEach element in the Array.Copy the code
Array.from()
The array.from () method creates a new, shallow copy of an Array instance from a similar Array or iterable.
console.log(Array.from('foo'));
// expected output: Array ["f", "o", "o"]
console.log(Array.from([1, 2, 3], x => x + x));
// expected output: Array [2, 4, 6]
Copy the code
grammar
Array.from(arrayLike[, mapFn[, thisArg]]) returns a new Array instance.Copy the code
Generate an array from a String
Array.from('foo');
// [ "f", "o", "o" ]
Copy the code
Generates an array from a Set
const set = new Set(['foo', 'bar', 'baz', 'foo']);
Array.from(set);
// [ "foo", "bar", "baz" ]
Copy the code
Generate arrays from array-like objects (arguments)
function f() { return Array.from(arguments); } f(1, 2, 3); // [1, 2, 3]Copy the code
The array is unmerged
function combine(){ let arr = [].concat.apply([], arguments); Return array. from(new Set(arr)); } var m = [1, 2, 2], n = [2,3,3]; console.log(combine(m,n)); / / [1, 2, 3]Copy the code
Array.isArray()
Array.isarray () is used to determine whether the value passed is an Array.
Example:
Array.isArray([1, 2, 3]);
// true
Array.isArray({foo: 123});
// false
Array.isArray("foobar");
// false
Array.isArray(undefined);
// false
Copy the code
Instanceof and isArray
When detecting Array instances, array. isArray is superior to instanceof because array. isArray can detect iframes.
var iframe = document.createElement('iframe'); document.body.appendChild(iframe); xArray = window.frames[window.frames.length-1].Array; Var arr = new xArray(1,2,3); // [1,2,3] // Correctly checking for Array Array. IsArray (arr); // true // Considered harmful, because doesn't work though iframes arr instanceof Array; // falseCopy the code
Polyfill
Example:
if (! Array.isArray) { Array.isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; }Copy the code
Array.of()
The array.of () method creates a new Array instance with a variable number of arguments, regardless of the number or type of the arguments.
The difference between array.of () and the Array constructor is that it handles integer arguments: array.of (7) creates an Array with a single element 7, while Array(7) creates an empty Array of length 7 (note: This means an array with seven empty, not seven undefined.
Array.of(7); // [7] Array.of(1, 2, 3); // [1, 2, 3] Array(7); // [ , , , , , , ] Array(1, 2, 3); / / [1, 2, 3]Copy the code
grammar
Array.of(element0[, element1[, ...[, elementN]]])
Copy the code
The sample
Array.of(1); // [1]
Array.of(1, 2, 3); // [1, 2, 3]
Array.of(undefined); // [undefined]
Copy the code
Old environment compatibility
if (! Array.of) { Array.of = function() { return Array.prototype.slice.call(arguments); }; }Copy the code
get Array[@@species]
Array[@@species] Accessor attribute Returns the constructor of an Array.
grammar
Array[Symbol.species]
Copy the code
The return value
The constructor for Array.
describe
Species accessor attribute Mandatory Array Default constructor for an object. The constructor of a subclass may override and change the assignment of the constructor.
The sample
The species attribute returns the default constructor, which is used for the Array constructor:
Array[Symbol.species]; // function Array()
Copy the code
closure
Closures allow you to access the scope of an inner function from within its outer function. In JavaScript, whenever a function is created, the closure is created at the same time as the function is created.
Lexical scope
Example:
function init() { var name = "Mozilla"; Function displayName() {// displayName() is an internal function, a closure alert(name); } displayName();} displayName(); } init();Copy the code
The word lexical refers to the lexical scope determining where a variable is available based on where the variable is declared in the source code. Nested functions have access to variables declared in their outer scope.
closure
Example:
function makeFunc() {
var name = "Mozilla";
function displayName() {
alert(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();
Copy the code
Closures are a combination of a function and the lexical context in which it is declared. The environment contains any local variables that were in scope when the closure was created.
Example:
// Add5 and add10 are closures. They share the same function definitions, but save different lexical environments. function makeAdder(x) { return function(y) { return x + y; }; } var add5 = makeAdder(5); var add10 = makeAdder(10); console.log(add5(2)); // 7 console.log(add10(2)); / / 12Copy the code
Example:
function MyObject(name, message) { this.name = name.toString(); this.message = message.toString(); this.getName = function() { return this.name; }; this.getMessage = function() { return this.message; }; } function MyObject(name, message) { this.name = name.toString(); this.message = message.toString(); } MyObject.prototype = { getName: function() { return this.name; }, getMessage: function() { return this.message; }}; function MyObject(name, message) { this.name = name.toString(); this.message = message.toString(); } MyObject.prototype.getName = function() { return this.name; }; MyObject.prototype.getMessage = function() { return this.message; };Copy the code
Inheritance and prototype chains
When it comes to inheritance, JavaScript has only one structure: objects. Each instance object has a private property (called __proto__) that points to its constructor’s prototype. The prototype object also has a prototype object of its own (__proto__), which is layered up until an object’s prototype object is null. By definition, NULL has no stereotype and serves as the last link in the stereotype chain.
Almost all objects in JavaScript are instances of objects at the top of the prototype chain.
A JavaScript object has a chain that points to a prototype object. When it tries to access a property of an object, it searches not only for that object, but also for the object’s prototype, and the prototype of the object’s prototype, ascending the hierarchy until it finds a property with a matching name or reaches the end of the stereotype chain.
Following the ECMAScript standard, the someObject.[[Prototype]] symbol is used to point to the Prototype of someObject. Starting with ECMAScript 6, [[Prototype]] can be accessed via object.getPrototypeof () and object.setPrototypeof () accessor. This is equivalent to JavaScript’s nonstandard but many browsers implement the __proto__ attribute.
Example:
// Let's create an object o from a function that has properties a and b: let f = function () {this.a = 1; this.b = 2; } function f() {this.a = 1; this.b = 2; } */ let o = new f(); // {a: 1, b: 2} // define the attribute f.rototype. b = 3; f.prototype.c = 4; // Do not directly define f. pertotype = {b:3,c:4}; O.[[Prototype]] has properties b and c // (o.__proto__ or O.[[Prototype]].[[Prototype]].[[Prototype]] is null. [[Prototype]] = null; / / in conclusion, the prototype chain are as follows: / / {a: 1, b: 2} - > {3, b: c: 4} - > Object. The prototype -- -- - > null console. The log (o.a); // 1 // is a property of O? Yes, the value of this property is 1 console.log(o.b); // 2 // is b a property of O? Yes, the attribute has a value of 2 // there is also a 'b' attribute on the stereotype, but it is not accessed. // This case is called "property shadowing" console.log(o.c); // 4 // is c a property of O? O.[[Prototype]]; // c = o.[[Prototype]]; Yes, the value of this property is 4 console.log(o.d); // is d a property of o? O.[[Prototype]] = // Prototype = o.[[Prototype]] // o.[[Prototype]].[[Prototype]] = nullCopy the code
Inherited methods
var o = { a: 2, m: function(){ return this.a + 1; }}; console.log(o.m()); // 3 // when calling o.m, 'this' refers to o. var p = object.create (o); // p is an object inherited from o p.a = 4; // Create p's own property 'a' console.log()); // p < p > p < p > p < p > p < p > p < p > p < p >Copy the code
Using prototypes in JavaScript
function doSomething(){} console.log( doSomething.prototype ); // Functions in JavaScript always have a default stereotype property, regardless of how they are declared. var doSomething = function(){}; console.log( doSomething.prototype );Copy the code
Console:
{constructor: ƒ doSomething(), __proto__: {constructor: ƒ Object(), hasOwnProperty: ƒ hasOwnProperty(), isPrototypeOf: ƒ isPrototypeOf(), propertyIsEnumerable: ƒ propertyIsEnumerable(), toLocaleString: ƒ toLocaleString(), toString: ƒ toString(), valueOf: ƒ valueOf()}}Copy the code
Add a new property to the prototype object of the doSomething function as follows:
function doSomething(){} doSomething.prototype.foo = "bar"; console.log( doSomething.prototype ); {foo: "bar", constructor: ƒ doSomething(), __proto__: {constructor: ƒ Object(), hasOwnProperty: ƒ hasOwnProperty(), isPrototypeOf: ƒ isPrototypeOf(), propertyIsEnumerable: ƒ propertyIsEnumerable(), toLocaleString: ƒ toLocaleString(), toString: ƒ toString(), valueOf: ƒ valueOf()}}Copy the code
An object created using a syntactic structure
var o = {a: 1}; // this Object inherits all the properties of object.prototype. // this Object has no property of its own named hasOwnProperty. // This property is a property of object.prototype // Object. Prototype is null // the prototype chain is as follows: // o ---> Object.prototype ---> null var a = ["yo", "whadup", "?"] ; // Array.prototype (array. prototype includes indexOf, forEach, etc.) // a ---> Array.prototype ---> Object.prototype ---> null function f(){ return 2; }}}}}}}}}}}}}}}} // f ---> Function.prototype ---> Object.prototype ---> nullCopy the code
An object created using a constructor
function Graph() { this.vertices = []; this.edges = []; } Graph.prototype = { addVertex: function(v){ this.vertices.push(v); }}; var g = new Graph(); // G is the generated object whose own properties are 'vertices' and 'edges'. // when g is instantiated, g.[[Prototype]] refers to graph.prototype.Copy the code
An Object created using object.create
You can call this method to create a new object. The prototype of the new object is the first argument passed when the create method is called:
var a = {a: 1}; // a ---> Object.prototype ---> null var b = Object.create(a); // b ---> a ---> Object.prototype ---> null console.log(b.a); Var c = object.create (b); // c ---> b ---> a ---> Object.prototype ---> null var d = Object.create(null); // d ---> null console.log(d.hasOwnProperty); // undefined because d does not inherit object.prototypeCopy the code
An object created using the class keyword
Keywords include class, constructor, static, extends, and super.
Example:
"use strict";
class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
class Square extends Polygon {
constructor(sideLength) {
super(sideLength, sideLength);
}
get area() {
return this.height * this.width;
}
set sideLength(newLength) {
this.height = newLength;
this.width = newLength;
}
}
var square = new Square(2);
Copy the code
❤️ follow + like + collect + comment + forward ❤️, original is not easy, encourage the author to create better articles
Like, bookmark and comment
I’m Jeskson, thanks to all the talented people: likes, favorites and comments, we’ll see you next time! ▌ I have to show you the truth. ▌ I have to show you the truth. I have to show you the truth.
See you next time!
Welcome to Star: github.com/webVueBlog/…