current position:Home>Front end mounting skill type 108 (II) -- no martial ethics
Front end mounting skill type 108 (II) -- no martial ethics
2021-08-27 05:43:22 【Fishing alone for cold river snow】
“ Xiao Ma , Recite 《 On My Modest Room 》.”“ The mountain is not high , If there is a fairy, there is a name . The water is not deep , A dragon is a spirit . Si is a humble house , Wei Xin .”“ stop , Why two words are missing ?”“ Young people don't talk about virtue .”
The style of the article is limited , References section , Will be marked at the end of the corresponding section .
Series of articles published summary :
- Front end mounting skills 108 type ( One )—— Workers
- Front end mounting skills 108 type ( Two )—— Don't talk about military morality
- Front end mounting skills 108 type ( 3、 ... and )—— No emotion API Call Engineer
- Front end mounting skills 108 type ( Four )—— Swing together
The 19th form : She should smile and frown , The ugly girl is tired —— window.btoa
、window.atob
, The name is so casual API What can be used for ?
In terms of naming alone , Two completely confusing API, What can we do with them ?( I even doubt , If you use this name in your project , It's possible to be beaten by colleagues , ha-ha )
window.atob()
Function is used to decode an object that has been base-64 Encoded data . You can usewindow.btoa()
The method is to Encode a data that may have problems during transmission , And after receiving the data , Usewindow.atob()
To decode data . for example : You can take ASCII The number in it 0 To 31 Control characters for encoding , Transmit and decode .window.btoa()
: take ASCII Convert string or binary data into a base64 Encoded string , This method can not be directly applied to Unicode character string .- In each browser , Use
window.btoa
Yes Unicode When a string is encoded, it will trigger an exception that the character is out of bounds . - The front end can use both API Yes URL Routing parameters 、 Sensitive information is transcoded , Prevent exposure of plaintext .
let encodedData = window.btoa('Hello, world'); // code
console.log(encodedData); // SGVsbG8sIHdvcmxk
let decodedData = window.atob(encodedData); // decode
console.log(decodedData); // Hello, world
let encodeUTF = window.btoa(encodeURIComponent(' ah '));
console.log(encodeUTF); // JUU1JTk1JThB
let decodedUTF = decodeURIComponent(atob(encodeUTF));
console.log(decodedUTF); // ah
Copy code
Reference :window.atob() And window.btoa() Methods to realize encoding and decoding | WindowOrWorkerGlobalScope.atob() | WindowOrWorkerGlobalScope.btoa()
The twentieth formula :escape
、encodeURI
、 encodeURIComponent
, These codes API What's the difference? ?
escape
Is a pair of strings (string) Encoding ( And the other two are right URL), The purpose is to make them readable on all computers . The effect of coding is%XX
perhaps%uXXXX
This form . among ASCII Letter 、 Numbers 、@*/+
, These characters are not encoded , The rest will . The key is , When you need to be right URL When coding , Please forget this method , This method is used for strings , Do not apply to URL;encodeURI
andencodeURIComponent
It's all coding URL, The only difference is the range of characters encoded ;encodeURI
Method does not encode the following characters :ASCII Letter 、 Numbers 、[email protected]#$&*()=:/,;?+'
;encodeURIComponent
Method does not encode the following characters :ASCII Letter 、 Numbers 、~!*()'
;- That is to say
encodeURIComponent
The range of coding is wider , Willhttp://XXX
Medium//
Also code , It can lead to URL Unavailable .( Actually java MediumURLEncoder.encode(str,char)
It's similar to this method , It can lead to URL Unavailable ). - Use scenarios :
- If it's just encoding strings , Don't URL It's half a dime , Then use
escape
, And this method is not usually used ; - If you need to code the entire URL, And then you need to use this URL, Then use
encodeURI
; - When you need to code URL When the parameter in , that
encodeURIComponent
It's the best way ; - In some cases , Coding causes URL Unavailable ( For example, the author has encountered some attachments when previewing attachments URL Problems that cannot be opened ), Try to consider whether it is caused by special characters .
- If it's just encoding strings , Don't URL It's half a dime , Then use
- If it doesn't work, it can be coded twice : On the reason of Double Coding
Reference :escape、encodeURI and encodeURIComponent The difference between
Formula 21 : Often encounter mobile terminal DNS Domain name hijacking ? Let's get to know HTTPDNS What is it? , What problems have been solved
For the Internet , Domain name is the first step to visit , And this jump is a lot of times “ Slip up ”( Especially the mobile network ), Causes access to error content 、 Failed connections, etc , Let the user swim on the Internet pleasant moment disappears . Any Internet enterprise that uses domain name to provide services to users , Are more or less unavoidable in the Internet environment with Chinese characteristics encountered in a variety of domain names are cached 、 There are some problems such as slow cross network access .
- DNS Analytic process :
- what HttpDNS:
HTTPDNS utilize HTTP Deal with the DNS Server interaction , Instead of the traditional based on UDP Agreed DNS Interaction , Bypassing the carrier's Local DNS, Effectively prevent domain name hijacking , Improve domain name resolution efficiency . in addition , because DNS The server gets the real client IP Instead of Local DNS Of IP, It can accurately locate the geographic location of the client 、 Operator information , Thus, the scheduling accuracy can be improved effectively .
-
HttpDNS The main problem to be solved :
- Local DNS hijacked : because HttpDns It's through IP Direct request HTTP Get server A Record the address , Do not ask local operators for existence domain Analytic process , So the hijacking problem has been avoided .
- Average access latency decreased : Because it is IP Direct access saves one visit domain Analytic process , After sorting by intelligent algorithm, find the fastest node to access .
- User connection failure rate decreased : Through the algorithm to reduce the previous failure rate of high server ranking , Improve server ranking with recently accessed data , Improve server ranking through historical access success records .
-
HttpDNS Principle
- client Direct access HttpDNS Interface , The access delay configured on the domain name configuration management system is optimal IP.( Based on disaster recovery considerations , Or do you want to keep the second choice LocalDNS How to resolve domain names );
- The client gets IP And then it goes straight to this IP Send service agreement request . With Http Request as an example , By means of header It is specified in host Field , towards HttpDNS Back to IP Send standard Http The request can be .
Details reference : Comprehensive understanding of mobile terminal DNS Domain name hijacking and other complications : principle 、 root 、HttpDNS Solutions, etc
The 22nd formula :depcheck
Find out if there are unused dependency packages in your front-end project
A lot of times , Maybe our front-end project is based on an existing project ” Copy build “, Or use it directly UmiJS Such an enterprise level react Application framework , Or based on Ant Design Pro And other open source projects , There will inevitably be unused dependent packages , Drag down project installation speed , Increase the packing volume of the project , At this time , We can consider using it depcheck
Find those unused dependent packages and remove them .
-
npm install depcheck -g
-
cd Go to the project directory to check , function depcheck
D:\project>depcheck Unused devDependencies # Unused dependencies * @antv/data-set * echarts * echarts-for-react * qs * Unused devDependencies # That is not used devDependencies * chalk * enzyme * express Missing dependencies # lack of dependencies * immutability-helper: .\src\components\EditColums\EditColumnsTable.js * slash2: .\config\config.js Copy code
UmiJS Learning reference :UmiJS | [react] First time to know Umi.JS
The 23rd form : Prevent misoperation , How to unload components 、 Routing jump 、 Page closing ( Refresh ) Prompt before
There are often large forms to fill in at work 、 Submit such requirements , If the user writes a lot of content , Because of misoperation , Refresh or close the page , Fill in the information with no cache , At this time, the user's heart should be broken .
React Component Uninstallation 、 Routing jump 、 Page closing ( Refresh ) Prompt before ( If it is AntD Modal Form in pop-up window , It can also be considered as appropriate maskClosable
Property is set to false, To prevent the closing of pop-up window due to delayed masking ):
// Listen to window events
useEffect(() => {
const listener = (ev) => {
ev.preventDefault();
ev.returnValue = ' Are you sure to leave ?';
};
window.addEventListener('beforeunload', listener);
return () => {
// Returns a function at the end
// React Call this method before the function component is unloaded. ( Realization componentWillUnmount)
window.removeEventListener('beforeunload', listener);
};
}, []);
Copy code
The 24th formula : Function calls can be performed without parentheses ?console.log`hello world` What will be printed out
- See the results directly :
console.log`hello world`; // Print out an array :["hello world", raw: Array(1)]
Copy code
- Take a look at the following code :
const name = 'jack';
const gender = false;
// Bracketed
console.log(`hey, ${name} is a ${gender ? 'girl' : 'boy'}.`); // hey, jack is a boy.
// Without brackets
console.log`hey, ${name} is a ${gender ? 'girl' : 'boy'}.`; // ["hey, ", " is a ", ".", raw: Array(3)] 'jack' 'boy'
Copy code
From the last line of printing, you can see that the items in the array are in the form of ' Insert expression ' Generated as a partition , And insert the content parameters in the table answer , It will also be printed out in turn . This is it. Template string with label .
- Syntax of template string :
// Ordinary
`string text` // Line break
`string text line 1 string text line 2` // interpolation
`string text ${expression} string text`;
// Template string with label
tag`string text ${expression} string text`;
Copy code
- What can be done :
const name = 'jack';
const gender = false;
function myTagFunc(strings, name, gender) {
const sex = gender ? 'girl' : 'boy';
// return 'hello world'
return strings[0] + name + strings[1] + sex + strings[2];
}
// result The value of is myTagFunc The return value of the function
// If myTagFunc return hello world,result Namely hello world
// This can avoid writing complex logic in the template string to a certain extent
const result = myTagFunc`hey, ${name} is a ${gender}.`;
console.log(result); // hey, jack is a boy.
Copy code
In the first argument of the tag function , There is a special property raw , We can use it to access the original string of template string , It is not replaced by special characters .
function tag(strings) {
console.log(strings.raw[0]);
}
tag`string text line 1 \n string text line 2`; // "string text line 1 \n string text line 2"
console.log`string text line 1 \n string text line 2`; // ["string text line 1 ↵ string text line 2", raw: Array(1)]
Copy code
Reference material :MDN- Template string with label | Template string with label
The 25th formula : Still using closures to implement auto increment ID? Why don't you try something elegant Generator?
- Closure
function createIdMaker() {
let id = 1;
return function () {
return id++;
};
}
const idMaker = createIdMaker();
console.log(idMaker()); // 1
console.log(idMaker()); // 2
console.log(idMaker()); // 3
Copy code
- Generator
function* createIdMaker() {
let id = 1;
while (true) yield id++;
}
const idMaker = createIdMaker();
console.log(idMaker.next().value); // 1
console.log(idMaker.next().value); // 2
console.log(idMaker.next().value); // 3
Copy code
The 26th formula : Young people don't speak martial arts , Who moved my object —— Object properties will queue themselves secretly ?
Only goddess in the eyes of programmers , There won't be objects , Even if there are , I can still be obedient to you ? If there is no object, then new One , Personalized customization , Absolute ideal type . You can't control the objects in reality. You can't control new Who came out ? in fact , you , Really not .
- Just imagine , In what order will the following code be output :
function Foo() {
this[200] = 'test-200';
this[1] = 'test-1';
this[100] = 'test-100';
this['B'] = 'bar-B';
this[50] = 'test-50';
this[9] = 'test-9';
this[8] = 'test-8';
this[3] = 'test-3';
this[5] = 'test-5';
this['D'] = 'bar-D';
this['C'] = 'bar-C';
}
var bar = new Foo();
for (key in bar) {
console.log(`index:${key} value:${bar[key]}`);
}
Copy code
stay ECMAScript The specification defines Numeric properties should be sorted in ascending order of index value , String properties are sorted in ascending order according to the order in which they were created . We call the numeric property of an object Sort properties , stay Chrome V8 engine Known as elements, String properties are called General properties , stay V8 Known as properties. stay V8 Inside , In order to effectively improve the performance of storing and accessing these two properties , Two linear data structures are used to store sorting attributes and general attributes respectively . meanwhile v8 Store some general properties directly into the object itself , We call this Properties within objects (in-object properties), However, the number of properties within an object is fixed , The default is 10 individual . For more details, please refer to my previous article How browsers work :Chrome V8 Make you understand better JavaScript —— 【V8 How are objects stored internally : Fast and slow attributes 】 section .
- The result is revealed
// Output :
// index:1 value:test-1
// index:3 value:test-3
// index:5 value:test-5
// index:8 value:test-8
// index:9 value:test-9
// index:50 value:test-50
// index:100 value:test-100
// index:200 value:test-200
// index:B value:bar-B
// index:D value:bar-D
// index:C value:bar-C
Copy code
Reference : How browsers work :Chrome V8 Make you understand better JavaScript
The 27th formula :VS Code There's a Google developer tools panel in it ? it and Chrome What does it matter ?
As shown in the figure below , Development tools that we often use VSCode It's so similar to a browser , Are they brothers who have been separated for many years ? EH , You don't have to say , That's interesting .( Click Help 【Help】 Under the Switch developer tools to open the following panel )
VS Code Is based on Electron ( Originally called Atom Shell) developable .Electron be based on Node.js( Run as back end ) and Chromium( Render as front end ), Enable developers to use HTML, CSS and JavaScript And other front-end technologies to develop cross platform desktop GUI Applications .Atom, GitHub Desktop, Slack, Microsoft Teams, WordPress Desktop And other well-known software is based on Electron Developed .Electron It's easier than you think , If you can build a website , You can build a desktop application .
VS Code The other major components of are :
- shell :Monaco Editor
- kernel :Language Server Protocol( A code editor )
- Debug Adapter Protocol
- Xterm.js
Reference material :vs code What technology is used in the interface ? | Electron | Electron Quick start
The 28th formula :"**********".slice(5 - rate, 10 - rate) —— A serious and evil package
Start to see the rating rate Component code , It's in an article full of evil Creed | A series of interview questions in , I always feel that this component does not correspond to the style of the article , I even thought it was smart enough , It is worth learning from , I'm not saved, isn't it , ha-ha .
{
let rate = 3;
'**********'.slice(5 - rate, 10 - rate);
}
Copy code
Reference material : Creed | A series of interview questions
Formula 29 :Uncaught TypeError: obj is not iterable
,for of
Error in traversing common objects , How to quickly make common objects available for of
Traverse ?
for of
Can iterate Arrays( Array ), Maps( mapping ), Sets( aggregate )、NodeList object 、Generator etc. , Even Strings( character string ) You can iterate , It can't traverse ordinary objects ?
// character string
const iterable = 'ES6';
for (const value of iterable) {
console.log(value);
}
// Output:
// "E"
// "S"
// "6"
// Common object
const obj = {
foo: 'value1',
bar: 'value2',
};
for (const item of obj) {
console.log(item);
}
// Uncaught TypeError: obj is not iterable
Copy code
Let's start with several methods of the object Object.values()
、Object.keys()
、Object.entries()
Look at it :
const obj = {
foo: 'value1',
bar: 'value2',
};
// Print by value Array of components
console.log(Object.values(obj));
// Print by key Array of components
console.log(Object.keys(obj));
// Print by [key, value] Two dimensional array of components
console.log(Object.entries(obj));
// Method 1 : Use of Methods of traversing common objects
for (const [, value] of Object.entries(obj)) {
console.log(value);
}
// General object transfer Map
console.log(new Map(Object.entries(obj)));
// Method 2 : Generated by traversing ordinary objects Map
for (const [, value] of new Map(Object.entries(obj))) {
console.log(value);
}
Copy code
Why can't ordinary objects be for of
Please refer to the form below for iteration .
The thirtieth form : Can traverse most data types for of
Why can't I traverse ordinary objects ?
- Why can't ordinary objects be
for of
iteration
{
// Array
const iterable = ['a', 'b'];
for (const value of iterable) {
console.log(value);
}
// Output:
// a
// b
}
{
// Set( aggregate )
const iterable = new Set([1, 2, 2, 1]);
for (const value of iterable) {
console.log(value);
}
// Output:
// 1
// 2
}
{
// Arguments Object( Parameter object )
function args() {
for (const arg of arguments) {
console.log(arg);
}
}
args('a', 'b');
// Output:
// a
// b
}
Copy code
You can see , These can be for of
Iterated objects , All of them have achieved one Symbol(Symbol.iterator)
Method , Ordinary objects do not have this method .
Simply speaking ,for of
Statement to create a loop to iterate over an iteratable object , Iteratable objects are implemented internally Symbol.iterator
Method , Ordinary objects do not implement this method , So ordinary objects are not iterative .
- How to achieve
Symbol.iterator
Method , Make common objects available tofor of
iteration
// Common object
const obj = {
foo: 'value1',
bar: 'value2',
[Symbol.iterator]() {
// Never mind [Symbol.iterator] Properties will be Object.keys() Get ,
// Symbol.iterator Need to pass through Object.getOwnPropertySymbols(obj) obtain ,
// Object.getOwnPropertySymbols() Method returns all of a given object itself Symbol Array of properties .
const keys = Object.keys(obj);
let index = 0;
return {
next: () => {
if (index < keys.length) {
return {
value: this[keys[index++]],
done: false,
};
} else {
return { value: undefined, done: true };
}
},
};
},
};
for (const value of obj) {
console.log(value); // value1 value2
}
Copy code
Reference material :MDN:for...of | Understanding the JavaScript For...of Loop(【 translation 】)| Iterator and for...of loop | Iterative protocol
Formula 31 :position Positioning only knows absolute
、fixed
、relative
and static
?,sticky
It can be amazing
- absolute: Generate absolute positioning elements , be relative to static Locate the first parent element other than location . Element position passed "left", "top", "right" as well as "bottom" Property defined .
- fixed: Generate absolute positioning elements , Positioning relative to the browser window . Element position passed "left", "top", "right" as well as "bottom" Property defined .
- relative: Generate relative positioning elements , Position relative to its normal position . therefore ,"left:20" To the elements LEFT Add 20 Pixels .
- static: The default value is . No location , Element appears in normal flow .
- sticky: Viscous positioning , The positioning is based on the user's scrolling position . When the element is in the screen , It acts like
position:relative;
, and When the page scrolls beyond the target area , It behaves likeposition:fixed;
, It will be fixed in the target position .
position:sticky
You can click here .
// usage :nav Viscous positioning of elements
nav {
position: -webkit-sticky;
position: sticky;
top: 0;
}
Copy code
Use position:sticky
In the process of , There may be some pits , For example, if you want to sticky take effect ,top Attribute or left attribute ( Look at the rolling direction ) It is necessary to have clear calculation value , otherwise fixed Will not show up . Please refer to 《CSS The world 》 By Zhang Xinxu Kill a rifle , Let's talk about it position:sticky Well .
Reference material :CSS position attribute | Kill a rifle , Let's talk about it position:sticky Well
Formula 32 :getBoundingClientRect
Let you find the right position and not lose yourself
- What is?
getBoundingClientRect
Element.getBoundingClientRect()
Method , Used to describe the specific location of an element , The four attributes of this position are relative to the position in the upper left corner of the viewport . Execute the method on a node , Its return value is one DOMRect Object of type . This object represents a rectangular box , It contains :left、top、right and bottom Read only properties such as , The specific meaning is shown in the figure below :
-
offset and getBoundingClientRect() difference
- offset Finger offset , Include all display widths taken up by this element in the document , Including scrollbars 、padding、border, barring overflow The hidden part ;
- offset The direction value of the parent needs to be taken into account , If the parent is an anchor element , So sub element of offset The value is relative to the parent element ; If the parent element is not an anchor element , So sub element of offset Value relative to the viewarea window ;
offsetParent
: Get the... Of the current element Locate the parent element :- If the parent element of the current element , Yes CSS location (position by absolute、relative、fixed), that
offsetParent
What you get is Current That parent element . - If the parent element of the current element , No, CSS location (position by absolute、relative、fixed), that
offsetParent
What you get is body.
- If the parent element of the current element , Yes CSS location (position by absolute、relative、fixed), that
- getBoundingClientRect() The value of is only relative to the viewable window , So it's easier in many scenarios “ Find the right place ”.
-
What can be done : Rolling ceiling effect
Before writing this section, I made a table pager fixed at the bottom of the browser 、 The effect of head rolling , It mainly refers to position:sticky
Properties and getBoundingClientRect
. When I read this section, I found that 【 Front end Dictionary 】5 A comparison of the ways to realize rolling ceiling suction [ Performance upgrade ] This article , This paper makes a detailed analysis and comparison of the five ways of ceiling suction , You can check it out if you're interested . meanwhile ,《CSS The world 》 Author Zhang Xinxu Kill a rifle , Let's talk about it position:sticky Well Yes sticky
Positioning is also detailed . I would like to talk about ceiling in the following chapter , Now it may need to be reassessed , ha-ha .
Example of rolling ceiling table :
【 Front end Dictionary 】5 A comparison of the ways to realize rolling ceiling suction [ Performance upgrade ] In the article, getBoundingClientRect
Top suction :
// html
<div class="pride_tab_fixed" ref="pride_tab_fixed">
<div class="pride_tab" :class="titleFixed == true ? 'isFixed' :''"> // some code </div>
</div>
// vue
export default {
data(){
return{
titleFixed: false
}
},
activated(){
this.titleFixed = false;
window.addEventListener('scroll', this.handleScroll);
},
methods: {
// Rolling monitoring , Head fixing
handleScroll: function () {
let offsetTop = this.$refs.pride_tab_fixed.getBoundingClientRect().top;
this.titleFixed = offsetTop < 0;
// some code
}
}
}
Copy code
Reference material :getBoundingClientRect Method | Kill a rifle , Let's talk about it position:sticky Well | 【 Front end Dictionary 】5 A comparison of the ways to realize rolling ceiling suction [ Performance upgrade ] | JS Medium offset、scroll、client summary
Formula 33 :Console Importer
Make your browser console a more powerful laboratory
In normal development , We often try some operations on the console ,Console Importer It's one that can be in Chrome Console Panel installation ( introduce )loadsh、moment、jQuery、React Plug ins for resources such as , The grammar is very simple , such as $i('moment')
You can introduce moment library , You can then verify it directly on the console 、 Use these libraries :
- Examples of use :
- design sketch :
- Introducing resource approach :
$i('jquery'); // Directly introducing
$i('[email protected]'); // Specify the version
$i('https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'); // cdn Address
$i('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'); // introduce CSS
Copy code
Formula 34 : misuse git reset --hard
, Am I really hopeless ? —— Get acquainted. git reflog
Time shuttle
- We went straight to the subject , Let's look at the following questions :
It took him a week to do it git log As shown below 6 Features , One for each function commit Submission of , Namely feature-1 To feature-6”:
Then the forced rollback is executed by mistake ,git reset --hard 2216d4e
, Rolled back to feature-1 On , And added when rolling back --hard, Before feature-2 To feature-6 All of the code is missing , Now? git log It is shown as follows :
then , On this basis, a new one is added commit Submit , Information is called feature-7:
Excuse me, : How to put the missing code feature-2 To feature-6 It's all back , also feature-7 And keep the code
-
Next , Let's recall a few git command :
git reset --hard
Undo all uncommitted changes in the workspace , Return both the staging and workspace to the previous version , And delete all previous information submitted , Use caution –hard Parameters , It will delete all information before the fallback point ;git log
The command displays all submitted version information ;git reflog
You can view a record of all operations for all branches ( Including those that have been deleted commit Record and reset The operation of );git cherry-pick
Role of command , Is to submit the specified (commit) Apply to other branches .
-
Last , Give the answer :
git reflog
andgit cherry-pick
- First , Use
git reflog
Check out so git Operation record , Write down the feature-7 and feature-6 Of hash code .
- secondly ,
git reset --hard cd52afc
Roll back to feature-6. At this point, we have completed half of the requirements : Success is back feature-6 On , however feature-7 be without . - Last ,
git cherry-pick 4c97ff3
, After the execution is complete ,feature-7 And the code is back , Be accomplished .
- First , Use
more git Recommended reading of knowledge points GitHub cofounder Scott Chacon and Ben Straub Open source masterpiece 《Pro Git》
Reference material :git Time shuttle -- The face of a goddess | git cherry-pick course | Git Reset Three models
Formula 35 : File upload will only be used form and Ant Design Upload Components ?
Recently, there is a need to make an interface provided by other departments , The interface document of uploading file is shown in the figure below , The content of the document is base64 Format , And pass along with other parameters . The author's previous needs , Uploading files is usually done through form、Ant Design Upload Components 、FormData Methods such as , Upload successfully and get one URL, What you will get when the form is submitted URL Pass to the back end ; Download via Blob、 Backend return URL、 Send E-mail 、 perhaps Front end generation Excel Methods such as . This upload uses FileReader, Simple record related implementation . On the upload and download of large files , It will be discussed in the following chapters .
- Code implementation
// DOM
<input type='file' id='file' onChange={(e) => this.uploadFile(e)} />
// js
uploadFile(e) {
const file = e.target.files[0];
const reader = new FileReader();
// Handle loadend event . This event is at the end of the read operation ( Or success , Or failure ) Trigger .
reader.onloadend = () => {
this.setState({
// Storage
XXXFile: {
// except name Outside ,file The properties that can be read from include size、type、lastModifiedDate
Name: file.name,
// base64 Format file data
// Send a large number of base64 Data can cause browser jams , The server side may also have problems receiving such data .
Buffer: reader.result.replace(/data.*base64[,]/, '')
}
})
}
reader.readAsDataURL(file);
}
Copy code
-
FileReader Method expansion :
FileReader.abort()
: Abort read operation . On return ,readyState The attribute is DONE.FileReader.readAsArrayBuffer()
: Start reading the specified Blob The content in , Once that is done , result Properties will be saved in the read file ArrayBuffer Data objects .FileReader.readAsBinaryString()
: Start reading the specified Blob The content in . Once that is done ,result Property will contain the raw binary data of the file being read .FileReader.readAsDataURL()
: Start reading the specified Blob The content in . Once that is done ,result Property will contain adata: URL
Format Base64 String to represent the contents of the read file .FileReader.readAsText()
: Start reading the specified Blob The content in . Once that is done ,result Property will contain a string to represent the contents of the file being read .
-
Reference materials for uploading other documents :
Formula 36 :2**53 === 2 ** 53 + 1
? without BigInt, How to sum large numbers ?
Number.MAX_SAFE_INTEGER
: The value is9007199254740991
, namely2 ** 53 - 1
, Less than this value can be accurately expressed . And then we'll find out2**53 === 2 ** 53 + 1
bytrue
.Number.MAX_VALUE
:: The value is1.7976931348623157e+308
, What is greater than the value isInfinity
, Be situated betweenInfinity
Cannot be represented exactly between and security values .
Since we can't add directly , We can use the method of dividing a string into an array of strings to add each bit .
- Implementation of large number addition
function add(str1, str2) {
// Converted to an array
str1 = (str1 + '').split('');
str2 = (str2 + '').split('');
let result = ''; // Store results
let flag = 0; // Store carry
while (str1.length || str2.length || flag) {
// Are there any additional bits or greater than 0 Carry of
// ~~str1.pop() Get the rightmost one , And turn it into numbers (~ Is the bitwise negation operator , See formula 14 for details )
// Add corresponding digits , Plus the carry
flag += ~~str1.pop() + ~~str2.pop();
// Remove carry , Then string splicing
result = (flag % 10) + result;
// carry ,0 or 1
flag = +(flag > 9);
}
// Remove the beginning ( High position ) Of 0
return result.replace(/^0+/, '');
}
// 2 ** 53:9007199254740992
// add(2**53, 1): "9007199254740993"
// 2**53+1: 9007199254740992
// BigInt result
// 2n**53n+1n:9007199254740993n
Copy code
- Add, subtract, multiply and divide :
The implementation of addition, subtraction, multiplication and division can be referred to Large number operation js Realization , The basic idea :
- Addition and subtraction of large numbers are the same thing , Since we can't add and subtract directly , We can use the way that strings are divided into arrays of strings .
- Multiplication : Multiply each digit by two , Finally, the dislocation is added .
Reference material :JS Add large numbers | The front end should know JavaScript The principle of floating point numbers and large numbers
This article is published in Personal blog , welcome Correct and star.
copyright notice
author[Fishing alone for cold river snow],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827054319340l.html
The sidebar is recommended
- Crazy blessing! Tencent boss's "million JVM learning notes", real topic of Huawei Java interview 2020-2021
- JS JavaScript how to get the subscript of a value in the array
- How to implement injection in vuex source code?
- JQuery operation select (value, setting, selected)
- One line of code teaches you how to advertise on Tanabata Valentine's Day - Animation 3D photo album (music + text) HTML + CSS + JavaScript
- An article disassembles the pyramid architecture behind the gamefi outbreak
- BEM - a front-end CSS naming methodology
- [vue3] encapsulate custom global plug-ins
- Error using swiper plug-in in Vue
- Another ruthless character fell by 40000, which was "more beautiful" than Passat and maiteng, and didn't lose BMW
guess what you like
-
Huang Lei basks in Zhang Yixing's album, and the relationship between teachers and apprentices is no less than that in the past. Netizens envy Huang Lei
-
He was cheated by Wang Xiaofei and Li Chengxuan successively. Is an Yixuan a blessed daughter and not a blessed home?
-
Zhou Shen sang the theme song of the film "summer friends and sunny days" in mainland China. Netizen: endless aftertaste
-
Pink is Wangyuan online! Back to the peak! The new hairstyle is creamy and sassy
-
Front end interview daily 3 + 1 - day 858
-
Spring Webflux tutorial: how to build reactive web applications
-
[golang] walk into go language lesson 24 TCP high-level operation
-
August 23, 2021 Daily: less than three years after its establishment, Google dissolved the health department
-
The female doctor of Southeast University is no less beautiful than the female star. She has been married four times, and her personal experience has been controversial
-
There are many potential safety hazards in Chinese restaurant. The top of the program recording shed collapses, and the artist will fall down if he is careless
Random recommended
- Anti Mafia storm: He Yun's helpless son, Sun Xing, is destined to be caught by his dry son
- Introduction to flex flexible layout in CSS -- learning notes
- CSS learning notes - Flex layout (Ruan Yifeng tutorial summary)
- Today, let's talk about the arrow function of ES6
- Some thoughts on small program development
- Talk about mobile terminal adaptation
- Unwilling to cooperate with Wang Yibo again, Zhao Liying's fans went on a collective strike and made a public apology in less than a day
- JS function scope, closure, let, const
- Zheng Shuang's 30th birthday is deserted. Chen Jia has been sending blessings for ten years. Is it really just forgetting to make friends?
- Unveil the mystery of ascension
- Asynchronous solution async await
- Analysis and expansion of Vue infinite scroll source code
- Compression webpack plugin first screen loading optimization
- Specific usage of vue3 video play plug-in
- "The story of huiyeji" -- people are always greedy, and fairies should be spotless!
- Installing Vue devtool for chrome and Firefox
- Basic usage of JS object
- 1. JavaScript variable promotion mechanism
- Two easy-to-use animation JS that make the page move
- Front end Engineering - scaffold
- Java SQL Server intelligent fixed asset management, back end + front end + mobile end
- Mediator pattern of JavaScript Design Pattern
- Array de duplication problem solution - Nan recognition problem
- New choice for app development: building mobile applications using Vue native
- New gs8 Chengdu auto show announces interior Toyota technology blessing
- Vieira officially terminated his contract and left the team. The national security club sent blessings to him
- Less than 200000 to buy a Ford RV? 2.0T gasoline / diesel power, horizontal bed / longitudinal bed layout can be selected
- How does "heart 4" come to an end? Pinhole was boycotted by the brand, Ma Dong deleted the bad comments, and no one blessed him
- We are fearless in epidemic prevention and control -- pay tribute to the front-line workers of epidemic prevention!
- Front end, netty framework tutorial
- Xiaomi 11 | miui12.5 | android11 solves the problem that the httpcanary certificate cannot be installed
- The wireless charging of SAIC Roewe rx5 plus is so easy to use!
- Upload and preview pictures with JavaScript, and summarize the most complete mybatis core configuration file
- [25] typescript
- CSS transform Complete Guide (Second Edition) flight.archives 007
- Ajax foundation - HTTP foundation of interview essential knowledge
- Cloud lesson | explain in detail how Huawei cloud exclusive load balancing charges
- Decorator pattern of JavaScript Design Pattern
- [JS] 10. Closure application (loop processing)
- Left hand IRR, right hand NPV, master the password of getting rich