Front end mounting skill type 108 (II) — no martial virtue

Time:2022-5-13

“Classmate Ma, recite the humble room inscription.” “If the mountain is not high, the immortal is named. If the water is not deep, the dragon is spirit. Si is a humble house, but sweet.” “Stop, why are there two words missing?” “Young people don’t speak my virtue.”

Summary of series articles:

Limited by the style of the article, the reference part will be marked at the end of the corresponding section.

The 19th style: the beauty should smile and frown, and the ugly woman’s effect is tiring——window.btoawindow.atob, what can such an arbitrarily named API do?

From the perspective of naming alone, what can we do with the two completely confusing APIs? (I even suspect that if such a name is used in the project, it may be beaten by colleagues, ha ha)

  • window.atob()Function is used to decode a data that has been encoded by base-64. You can usewindow.btoa()Method toEncode a data that may have problems during transmission, and after receiving the data, usewindow.atob()Method to decode the data. For example, you can encode, transmit and decode the control characters with values from 0 to 31 in ASCII.
  • window.btoa(): convert ascii string or binary data into a Base64 encoded string,This method cannot act directly on Unicode strings
  • In each browser, usewindow.btoaEncoding a Unicode string will trigger a character out of bounds exception.
  • The front end can use these two APIs to transcode URL routing parameters, sensitive information, etc. to prevent plaintext exposure.
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

Reference:window. Atob () and window Coding and decoding with btoa () method | WindowOrWorkerGlobalScope.atob() | WindowOrWorkerGlobalScope.btoa()

Formula 20:escapeencodeURIencodeURIComponent, what are the differences between these coding APIs?

  • escapeIt encodes strings (and the other two are URLs) to make them readable on all computers. The effect after coding is%XXperhaps%uXXXXThis form. Where ASCII letters, numbers@*/+, these characters will not be encoded, the rest will. Most importantly,When you need to encode the URL, please forget this method. This method is used for strings and is not applicable to URLs
  • encodeURIandencodeURIComponentAll are encoded URLs. The only difference is the character range of the encoding;
  • encodeURIMethod does not encode the following characters: ASCII letters, numbers[email protected]#$&*()=:/,;?+'
  • encodeURIComponentMethod does not encode the following characters: ASCII letters, numbers~!*()'
  • that isencodeURIComponentA wider range of codes, willhttp://XXXMedium//It is also encoded, which will make the URL unavailable. (in fact, in Java)URLEncoder.encode(str,char)It is also similar to this method, which will make the URL unavailable).
  • Usage scenario:

    • If it’s just an encoded string and doesn’t have a half dime relationship with the URL, useescapeAnd this method is generally not used;
    • If you need to encode the entire URL and then need to use this URL, useencodeURI
    • When you need to encode the parameters in the URL, thenencodeURIComponentIs the best way;
    • In some scenarios, the URL is unavailable after encoding (for example, the author has encountered the problem that some attachment URLs cannot be opened when previewing attachments). You can try to consider whether it is caused by special characters.
  • If it does not take effect, it can be coded twice:About the reason of twice coding

Reference:The difference between escape, encodeuri and encodeuricomponent

Style 21: This is not the page I visit – often encounter the problem of DNS domain name hijacking on the mobile terminal? Let’s learn what httpdns is and what problems it has solved

For the Internet, domain name is the first jump of access, and this jump will often “slip” (especially the mobile terminal network), resulting in access to wrong content, failed connection, etc., which makes the user’s refreshing moment of swimming on the Internet disappear. However, Internet enterprises that use domain names to provide services to users can not avoid more or less the problems of caching of various domain names and slow cross network access of users in the Internet environment with Chinese characteristics.

  • DNS resolution process:

Front end mounting skill type 108 (II) -- no martial virtue

  • What httpdns:

   httpdns uses HTTP protocol to interact with DNS server, replacing the traditional DNS interaction based on UDP protocol and bypassing the local DNS of operators,It effectively prevents domain name hijacking and improves the efficiency of domain name resolution。 In addition, because the DNS server obtains the real client IP instead of the local DNS IP,It can accurately locate the geographical location and operator information of the client, so as to effectively improve the scheduling accuracy

  • Httpdns mainly solves the following problems:

    • Local DNS hijacking: because httpdns directly requests HTTP to obtain the server a record address through IP, there is no process of asking the local operator for domain resolution, so the hijacking problem is fundamentally avoided.
    • The average access delay decreases: because it is IP direct access, a domain parsing process is omitted. The fastest node is found for access after sorting through intelligent algorithm.
    • Decline in user connection failure rate: reduce the ranking of servers with high failure rate in the past through algorithms, improve the ranking of servers through recently accessed data, and improve the ranking of servers through historical access success records.
  • Principle of httpdns

    • clientDirect access to httpdns interface, obtain the IP with the best access delay configured by the service on the domain name configuration management system. (based on the consideration of disaster recovery, the second choice is to use the operator’s localdns to resolve the domain name);
    • After the client obtains the IP, it directly sends a service protocol request to the IP. Take the HTTP request as an example. By specifying the host field in the header, you can send a standard HTTP request to the IP returned by httpdns.

For details, please refer to:Fully understand the mobile DNS domain name hijacking and other complications: principle, root cause, httpdns solution, etc

Formula 22:depcheckCheck whether there are unused dependent packages in your front-end project

  many times, our front-end projects may be “copied and built” based on an existing project or used directlyUmiJSSuch an enterprise level react application framework, or based onAnt Design ProWhen we delete or modify open source projects, it is inevitable that unused dependent packages will be installed, which will drag down the installation speed of the project and increase the packaging volume of the project. At this time, we can consider using themdepcheckFind those unused dependent packages and remove them.

  • npm install depcheck -g
  • CD to the project directory to be checked and run depcheck

    D:\project>depcheck
      Unused devdependencies # unused dependencies
        * @antv/data-set
        * echarts
        * echarts-for-react
        * qs
      *Unused devdependencies # unused devdependencies
        * chalk
        * enzyme
        * express
      Missing dependencies # missing dependencies
        * immutability-helper: .\src\components\EditColums\EditColumnsTable.js
        * slash2: .\config\config.js

Umijs learning reference:UmiJS | [react] first met UMI JS

Formula 23: to prevent misoperation, how to prompt before component unloading, route jump and page closing (refresh)

There is often a need to fill in and submit large forms at work. If a user writes a lot of content, he refreshes or closes the page due to misoperation, and the filled information is not cached, the user’s heart should be broken.

   prompt before unloading the react component, route jump and closing (refreshing) the page (if it is a form in the antd modal pop-up window, it can also be considered as appropriate)maskClosableProperty is set to false to prevent pop ups from closing due to delayed masking):

//Listen for 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 calls this method before the function component is unloaded (implements componentwillunmount)
    window.removeEventListener('beforeunload', listener);
  };
}, []);

Formula 24: can function calls be executed without parentheses? console. What will log \ ` Hello world \ ` print out

  • Look at the results directly:
console. Log ` Hello world ` // print out an array: ["Hello world", raw: array (1)]
  • Look at the following code:
const name = 'jack'
const gender = false
//Parenthesized
console.log(`hey, ${name} is a ${gender ? 'girl' : 'boy'}.`) // hey, jack is a boy.
//Without parentheses
console.log`hey, ${name} is a ${gender ? 'girl' : 'boy'}.` // ["hey, ", " is a ", ".", raw: Array(3)] 'jack' 'boy'

   from the printing of the last line, it can be seen that the items in the array are generated by ‘insert expression’ as segmentation, and the content parameters inserted into the table answer will also be printed in turn. This is it.Tagged template string

  • Syntax of template string:
//Ordinary
`string text`

//Line feed
`string text line 1
 string text line 2`

//Interpolation
`string text ${expression} string text`

//Tagged template string
tag `string text ${expression} string text`
  • 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]
}

//The value of result is the return value of the mytagfunc function
//If mytagfunc returns Hello world, the result is 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.

In the first parameter of the tag function, there is a special attribute raw, through which we can access the original string of the template string without the replacement of 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)]

Front end mounting skill type 108 (II) -- no martial virtue

reference material:MDN tagged template string | Tagged template string

Formula 25: are you still using closures to realize self increment ID? Why not try the 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
  • 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

Style 26: young people don’t talk about martial virtue. Who moved my object – the object attribute will secretly queue up by themselves?

In the eyes of programmers, there are only goddesses, and there will be no objects. Even if there are, can they be impeccable and obedient? Lack of objects, then new one, personalized customization, absolutely ideal. Can’t control the objects in reality, and can’t control the objects out of new? In fact, you really can’t.

  • Imagine in what order the following code will 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]}`);
}

  inECMAScript specificationDefined inNumeric attributes should be arranged in ascending order according to the size of the index value, and string attributes should be arranged in ascending order according to the order when they were created。 We call numeric attributes in objectsSort attribute, in the chrome V8 engine, it is called elements, and string attributes are calledGeneral properties, called properties in V8. In V8, in order to effectively improve the performance of storing and accessing these two attributes, two linear data structures are used to save sorting attributes and general attributes respectively. At the same time, V8 stores some general attributes directly into the object itself, which we callIn object propertiesHowever, the number of attributes in the object is fixed, and the default is 10. For more details, please refer to a previous article by the authorHow browsers work: Chrome V8 makes you understand JavaScript better——[how to store objects in V8: fast attribute and slow attribute] section.

  • The results were announced
//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

Reference:How browsers work: Chrome V8 makes you understand JavaScript better

Formula 27: is there a Google developer tool panel in vs Code? What does it have to do with chrome?

As shown in the figure below, the development tool vscode we often use is so similar to the browser. Are they brothers who have been separated for many years? Well, don’t say it yet. It’s really interesting. (click switch developer tool under help to open the following panel)

Front end mounting skill type 108 (II) -- no martial virtue

  vs code is developed based on electron (formerly atom shell). Electron is based on node JS (as the back-end runtime) and chromium (as the front-end rendering) enable developers to use front-end technologies such as HTML, CSS and JavaScript to develop cross platform desktop GUI applications. Atom, GitHub desktop, slack, Microsoft teams, WordPress desktop and other well-known software are developed based on electron.Electron is simpler than you think. If you can build a website, you can build a desktop application

Other main components of vs code are:

reference material:What technology is used in the vs code interface? | Electron | Electron quick start

The 28th type: “★★★★★☆☆☆☆☆ Slice (5 – rate, 10 – rate) – a serious and evil component package

  I began to see this line of code for rating rate components in an article full of evil spiritCreed | hand tearing and hanging interviewer series interview questionsIn, I always feel that this component does not correspond to the style of the article, and even think that this implementation is smart enough to be used for reference. Am I hopeless, ha ha.

{
  let rate = 3;
  "★★★★★☆☆☆☆☆".slice(5 - rate, 10 - rate);
}

reference material:Creed | hand tearing and hanging interviewer series interview questions

Formula 29:Uncaught TypeError: obj is not iterablefor ofWhen traversing ordinary objects, an error is reported. How to quickly make ordinary objects availablefor ofTraversal?

  for ofYou can iterate arrays, maps, sets, NodeList objects, generators, etc. even strings can iterate, but you can’t traverse ordinary objects?

//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

  let’s start with several methods of objectsObject.values()Object.keys()Object.entries()Look:

const obj = {
  foo: 'value1',
  bar: 'value2'
}
//Print an array of values
console.log(Object.values(obj))

//Print an array of keys
console.log(Object.keys(obj))

//Print a two-dimensional array composed of [key, value]
console.log(Object.entries(obj))

//Method 1: use of to traverse ordinary objects
for(const [, value] of Object.entries(obj)){
  console.log(value)
}

//General object to map
console.log(new Map(Object.entries(obj)))

//Method 2: traverse the map generated by ordinary objects
for(const [, value] of new Map(Object.entries(obj))){
  console.log(value)
}

  why can’t ordinary objects befor ofPlease refer to the following table for iteration.

Formula 30: it can traverse most data typesfor ofWhy not traverse ordinary objects?

  • Why can’t ordinary objects befor ofiteration
{
  //Array
  const iterable = ['a', 'b'];
  for (const value of iterable) {
    console.log(value);
  }
  // Output:
  // a
  // b
}
{
  //Set
  const iterable = new Set([1, 2, 2, 1]);
  for (const value of iterable) {
    console.log(value);
  }
  // Output:
  // 1
  // 2
}
{
//Arguments object
function args() {
  for (const arg of arguments) {
    console.log(arg);
  }
}
args('a', 'b');
// Output:
// a
// b
}

Front end mounting skill type 108 (II) -- no martial virtue

Front end mounting skill type 108 (II) -- no martial virtue

Front end mounting skill type 108 (II) -- no martial virtue

  as you can see, these can befor ofIterative objects have implemented oneSymbol(Symbol.iterator)Method, which ordinary objects do not have.

  in short,for ofStatement creates a loop to iterate over the iteratable object, which is implemented internallySymbol.iteratorMethod, and ordinary objects do not implement this method, so ordinary objects are not iterative.

  • How to achieveSymbol.iteratorMethod so that ordinary objects can befor ofiteration
//Common object
const obj = {
  foo: 'value1',
  bar: 'value2',
  [Symbol.iterator]() {
    //Don't worry that the [symbol. Iterator] attribute will be replaced by object Keys() obtained,
    // Symbol. Iterator needs to pass object Getownpropertysymbols (obj),
    // Object. The getownpropertysymbols () method returns an array of all symbol properties of a given object itself.
    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
}

   the above is implemented for objSymbol.iteratorAfter the interface, we can even convert objects into arrays as follows:

console.log([...obj]); // ["value1", "value2"]
console.log([...{}]); // console.log is not iterable (cannot read property Symbol(Symbol.iterator))

  more aboutfor...ofCan refer to the author’sThis article takes you to understand: you can iterate over most data types of for… Of. Why can’t you traverse ordinary objects?

reference material:MDN:for…of | Understanding the JavaScript For…of Loop[translation])| Iterator and for Of cycle | Iterative protocol

Type 31: position positioning only knowsabsolutefixedrelativeandstatic?,stickyActually, it can be amazing

  • Absolute: generates an element with absolute positioning, which is positioned relative to the first parent element other than static positioning. The position of the element is specified by the “left”, “top”, “right” and “bottom” attributes.
  • Fixed: generates an absolutely positioned element, which is positioned relative to the browser window. The position of the element is specified by the “left”, “top”, “right” and “bottom” attributes.
  • Relative: generates a relatively positioned element, which is positioned relative to its normal position. Therefore, “left: 20” adds 20 pixels to the left position of the element.
  • Static: default value. Without positioning, the element appears in the normal flow.
  • sticky:Viscous positioning, the positioning is based on the position where the user scrolls. When an element is on the screen, it behaves likeposition:relative;, andWhen the page scrolls beyond the target area, it behaves likeposition:fixed;, it will be fixed in the target position.

  position:stickyThe amazing ceiling effect can be clickedhere

//Usage: NAV element to achieve sticky positioning
nav {
    position: -webkit-sticky;
    position: sticky;
    top: 0;
}

  useposition:stickyThere may be some holes in the process of. For example, in order for sticky to take effect, the top attribute or left attribute (depending on the rolling direction) must have a clear calculated value, otherwise the fixed performance will not appear. For details, please refer to the comments of Zhang Xinxu, the author of CSS worldKill a comeback. Let’s talk about position: sticky

reference material:CSS position property | Kill a comeback. Let’s talk about position: sticky

The 32nd move: you can do benevolence and righteousness by your side. It’s better for me to know it——getBoundingClientRectLet you find the right position and don’t lose yourself

  • What is?getBoundingClientRect

  Element.getBoundingClientRect()Method is used to describe the specific position of an element. The four attributes of the position are relative to the position of the upper left corner of the viewport. Execute this method on a node, and its return value is an object of type domrect. This object represents a rectangular box, which contains read-only attributes such as left, top, right and bottom. The specific meaning is shown in the following figure:

Front end mounting skill type 108 (II) -- no martial virtue

  • Difference between offset and getboundingclientrect()

    • Offset refers to the offset, including all the display widths occupied by this element in the document, including scroll bar, padding and border, excluding the hidden part of overflow;
    • The direction value of offset needs to consider the parent. If the parent is a positioning element, the offset value of the child element is relative to the parent element; If the parent element is not a positioning element, the offset value of the child element is relative to the viewable area window;
    • offsetParent: gets the of the current elementLocate parent element

      • If the parent element of the current element,CSS positioning(position is absolute, relative and fixed), thenoffsetParentWhat you get iscurrentThe parent element.
      • If the parent element of the current element,No CSS positioning(position is absolute, relative and fixed), thenoffsetParentWhat you get isbody
    • The value of getboundingclientrect() is only relative to the viewable area window, so it is easier to “find and locate” in many scenarios.
  • What can be done: rolling ceiling effect

   before writing this section, the author has made an effect of fixing the table pager at the bottom of the browser and scrolling and ceiling of the header, which is mainly referred toposition:stickyProperties andgetBoundingClientRect。 I found this section when I checked it[front end dictionary] comparison of five implementation methods of rolling ceiling (performance upgraded version)This article makes a detailed analysis and comparison of five ceiling methods. You can have a look if you are interested. At the same time, Zhang Xinxu, the author of CSS world, is hereKill a comeback. Let’s talk about position: stickyyesstickyPositioning is also described in detail. Originally I wanted to talk about ceiling in the following chapters. Now it may need to be reassessed, ha ha.

Example of rolling ceiling table:

Front end mounting skill type 108 (II) -- no martial virtue

  [front end dictionary] comparison of five implementation methods of rolling ceiling (performance upgraded version)In the articlegetBoundingClientRectCeiling implementation:

// 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 monitor, head fixed
      handleScroll: function () {
        let offsetTop = this.$refs.pride_tab_fixed.getBoundingClientRect().top;
        this.titleFixed = offsetTop < 0;
        // some code
      }
    }
  }

reference material:Getboundingclientrect method | Kill a comeback. Let’s talk about position: sticky | [front end dictionary] comparison of five implementation methods of rolling ceiling [performance upgraded version] | Summary of offset, scroll and client in JS

Formula 33:Console ImporterMake your browser console a more powerful experimental field

  in normal development, we often try some operations on the console,Console ImporterIt is a plug-in that can install (import) loadsh, moment, jQuery, react and other resources on the chrome console panel. The syntax is also very simple, such as$i('moment')You can import the moment library, and then directly verify and use these libraries on the console:

  • Use example:

Front end mounting skill type 108 (II) -- no martial virtue

  • design sketch:

Front end mounting skill type 108 (II) -- no martial virtue

  • Method of introducing resources:
$I ('jquery ') // direct import
$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 '// importing CSS

Link:Console Importer | Chrome web store address

Formula 34: misusegit reset --hard, am I really hopeless—— Get to know each othergit reflogTime shuttle

  • Let’s go straight to the subject and look at the following questions first:

Ignorant Xiaobai spent a week doing the following six functions of GIT log. Each function corresponds to a commit submission, which are “feature-1 to feature-6”:

Front end mounting skill type 108 (II) -- no martial virtue

   then the forced rollback is executed incorrectly,git reset --hard 2216d4e, rolled back to feature-1, and added — hard when rolling back, resulting in all the codes from feature-2 to feature-6 lost. Now the GIT log is displayed as follows:

Front end mounting skill type 108 (II) -- no martial virtue

Then, on this basis, a new commit submission information is added, which is called feature-7:

Front end mounting skill type 108 (II) -- no martial virtue

How to recover all the lost code from feature-2 to feature-6, and keep the code of feature-7

  • Next, let’s recall several git commands:

    • git reset --hardUndo all uncommitted modifications in the workspace, return the staging area and workspace to the previous version, and delete all previous information submissions. Use the – hard parameter carefully, which will delete all information before the fallback point;
    • git logThe command can display all submitted version information;
    • git reflogYou can view all operation records of all branches (including deleted commit records and reset operations);
    • git cherry-pickThe function of the command is to apply the specified commit to other branches.
  • Finally, the answer is given:git reflogandgit cherry-pick

    • First, usegit reflogCheck all git operation records and write down the hash codes of feature-7 and feature-6.

    Front end mounting skill type 108 (II) -- no martial virtue

    • secondly,git reset --hard cd52afcRoll back to feature-6. At this point, we have completed half of the requirements: we have successfully returned to feature-6, but feature-7 is gone.
    • last,git cherry-pick 4c97ff3, after the execution is completed, the code of feature-7 comes back and is completed.

For more git knowledge points, it is recommended to read the open source masterpiece of GitHub co founders Scott Chacon and Ben Straub《Pro Git》

reference material:Git time shuttle — goddess’s profile | Git cherry pick tutorial | Git reset three modes

Type 35: only form and Ant Design upload components will be used for file upload?

   recently, there is a need to make an interface provided by other departments. The interface document for uploading files is shown in the figure below. The file content is in Base64 format and should be transmitted together with other parameters. According to the requirements made by the author in the past, the uploaded files are generally uploaded through form, ant design upload component, formdata and other methods. A URL is obtained after successful upload, and the URL is transmitted to the back end when the form is submitted; Download through blob, back-end return URL, send email, orGenerate excel from the front endAnd so on. This upload has been usedFileReader, simply record the relevant implementation. The upload and download of large files will be discussed in the following chapters.

Front end mounting skill type 108 (II) -- no martial virtue

  • FileReader upload 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 the load event. This event is triggered at the end of the read operation (either successful or failed).
    reader.onloadend = () => {
      this.setState({
        //Store
        XXXFile: {
          //In addition to name, the readable attributes in file include size, type and lastmodifieddate
          Name: file.name,
          //Base64 format file data
          //Sending a large amount of Base64 data at one time will cause the browser to get stuck, and the server may also have problems receiving such data.
          Buffer: reader.result.replace(/data.*base64[,]/, '')
        }
      })
    }
    reader.readAsDataURL(file);
  }
  • FileReader method extension:

    • FileReader.abort(): abort read operation. On return, the readyState property is done.
    • FileReader.readAsArrayBuffer(): start reading the contents of the specified blob. Once completed, the arraybuffer data object of the read file will be saved in the result attribute
    • FileReader.readAsBinaryString(): start reading the contents of the specified blob. Once completed, the result attribute will contain the original binary data of the read file.
    • FileReader.readAsDataURL(): start reading the contents of the specified blob. Once completed, the result attribute will contain adata: URLBase64 string in format to represent the contents of the read file.
    • FileReader.readAsText(): start reading the contents of the specified blob. Once completed, the result attribute 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? How to sum large numbers without bigint?

  • Number.MAX_SAFE_INTEGER: value is9007199254740991, i.e2 ** 53 - 1, less than this value can be expressed accurately. Then we’ll find out2**53 === 2 ** 53 + 1bytrue
  • Number.MAX_VALUE:: value is1.7976931348623157e+308, more than that is worth itInfinity, betweenInfinityAnd safety values cannot be accurately represented.

Since we can’t add directly, we can add each bit by dividing the string into a string array.

  • Implementation of large number addition
function add (str1, str2) {
    //Convert to single string array
    str1=(str1+'').split('');
    str2=(str2+'').split('');
    let result='';// Store results
    let flag=0; //  Store carry
    While (STR1. Length | STR2. Length | flag) {// is there any bit that is not added or carry greater than 0
    // ~~str1. Pop() gets the rightmost bit and turns it into a number (~ is the bitwise negation operator, see formula 14 for details)
    //Add the corresponding digits and add the carry
        flag += ~~str1.pop() + ~~str2.pop();
    //Remove the carry, and then splice the string
        result = flag%10 + result;
    //Carry, 0 or 1
        flag = +(flag>9);
    }
  //Remove the 0 at the beginning (high order)
  return result.replace(/^0+/, '');
};
// 2 ** 53:9007199254740992
// add(2**53, 1): "9007199254740993"
// 2**53+1: 9007199254740992
//Bigint results
// 2n**53n+1n:9007199254740993n
  • add , subtract , multiply and divide:

  for the implementation of addition, subtraction, multiplication and division, please refer toJS implementation of large number operation, basic idea:

1. Addition and subtraction of large numbers is the same truth. Since we can't realize direct addition and subtraction, we can use the way of dividing strings into string arrays.
2. Multiplication: each digit is multiplied by two, and finally added by dislocation.

reference material:JS addition of large numbers | The front end should know the principle of JavaScript floating-point numbers and large numbers

This article was first published inPersonal blog, welcomeCorrection and star