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 :

The 19th form : She should smile and frown , The ugly girl is tired —— window.btoawindow.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 use window.btoa() The method is to Encode a data that may have problems during transmission , And after receiving the data , Use window.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 :escapeencodeURIencodeURIComponent, 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 and encodeURIComponent 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 , Will http://XXX Medium // Also code , It can lead to URL Unavailable .( Actually java Medium URLEncoder.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 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 :

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 

 Original string

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 )

VSCode

  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 :

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 

iterator1

iterator2

iterator3

   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 to for 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 absolutefixedrelative 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 like position: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 :

getBoundingClientRect

  • 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.
    • 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 :

position

  【 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 :

import

  • design sketch :

Console Importer

  • 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 

link :Console Importer | Chrome Web Store Address

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”:

git1

   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 :

git2

   then , On this basis, a new one is added commit Submit , Information is called feature-7:

git3

   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 and git cherry-pick

    • First , Use git reflog Check out so git Operation record , Write down the feature-7 and feature-6 Of hash code .

    git4

    • 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 .

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 .

fileupload

  • 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 a data: 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 is 9007199254740991, namely 2 ** 53 - 1, Less than this value can be accurately expressed . And then we'll find out 2**53 === 2 ** 53 + 1 by true.
  • Number.MAX_VALUE:: The value is 1.7976931348623157e+308, What is greater than the value is Infinity, Be situated between Infinity 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

Random recommended