The problem the forerunner

  • gridUnderstanding and Using layout [CSS]
  • for inandfor of【 jS Basics 】
  • ajax,axiosandfetch【 jS Basics 】
  • What are the methods for array traversal? What’s the difference? 【 JS Basics 】
  • What is the difference between Template and JSX?
  • Vue initialization page flicker
  • Vue.extend【Vue】
  • To separate numbers by commas in thousandths of a digit.
  • Implement the addition of non-negative large integers
  • Implement add(1)(2)(3) equal to add(1, 2)(3)
  • Code output (Promise related)

Knowledge comb

Understanding and using grid layouts

A grid layout, also known as a grid layout, is a two-dimensional layout that uses grid elements just like a table. Grid layout allows you to align elements by row or column. In terms of layout, however, grids are more possible or easier than tables. For example, the child elements of a grid container can position themselves so that they are truly overlapping and hierarchical like CSS positioned elements.

To use a grid layout, we need to set the element’s display to grid or inline-grid.

Some basic concepts of grid layout:

Track (row)

A grid is like a table with rows and columns divided into multiple grid cells. A row or column can be called a track of the grid. Use grid-template-columns and grid-template-rows to set the column layout, respectively. Values take many forms:

  • Pixels or percentages: e.ggrid-template-columns: 100px 20% 20% auto;Represents a grid layout divided into four columns.
  • Scale layout: Use special unitsfr, can be used to represent the ratio of cells, such as100px 1fr 2frIndicates that the grid is divided into three columns, with the first column occupying 100px width and the remaining two columns as follows1:2The proportion is equally divided.
  • Repeat functionrepeat:repeat(3, 1fr 2fr)repeating1fr 2frThree times.
  • Length boundaries: Sometimes we want a minimum or maximum width to be usedminmaxTo set, for exampleminmax(100px, auto)Indicates that the minimum length of a row or column is 100px, and the maximum size is automatically expanded based on the content.
  • Elastic layout: Sometimes we cannot determine the number of columns, so we can use itauto-fillTo set up the dynamic box model:repeat(auto-fill, minmax(100px, auto))In this way, the box ADAPTS to the overall length to adjust the number of columns.

Grid lines

Once we have designed the column and column values of the grid, we can divide the grid area in detail, which requires the use of grid lines.

It should be noted that when we define grids, we define grid tracks, not grid lines. Grid creates numbered Grid lines for us to locate each Grid element. For example, the following grid has four vertical gridlines in three columns and two rows.

By default, each child element occupies one grid cell. If you need a child element to occupy more than one cell, you can use grid-column-start, grid-column-end, grid-row-start, and grid-row-end to control which grid lines surround the cell.

It is worth noting that we can also make two cells overlap and share a part of the network cells, which will result in occlusion overlay effect. We can use z-index to control the level of cells.

The grid spacing

Use grid-column-gap and grid-row-gap to set row spacing.

other

At this point, the basic use of the grid layout is complete, with some details that can be controlled through other properties. Commonly used are:

  • justify-content: Sets the cellHorizontal alignment, similar toflexThe layout of thejustify-content, the property names are the same, but the optional values are different.
  • align-content: Sets the vertical alignment of cells, similarlyflexThe layout of thealign-items, the optional values are also different, but it is worth noting that,flexThere are alsoalign-contentProperty that defines the alignment of multiple axes.
  • place-content: The sum of the above two properties isplace-content.
  • grid-auto-flow: To set the grid flow direction, the default is first column, that is, from left to right and then from top to bottom, we can also change tocolumnSo that the flow direction becomes column first and row after rowflexIn theflex-directionSimilarly, besidesflexThere’s one moreflex-wrapTo control the way the line breaks, the combination of the two properties isflex-flowProperties.

There are some other properties to refer to: CSS Grid Layout tutorial.

Reference:

  • Grid layout – MDN
  • Basic concepts of grid layout
  • Grid Layout and other layout methods
  • CSS Grid Layout tutorial

The difference between for in and for of

The for… “Of” is a new iteration method in ES6 that allows you to iterate over a data structure (array, object, etc.) containing an iterator interface and return the value of each item. The difference between in is as follows:

  • The for… The of traversal returns the key value of the object, for… In gets the key name of the object.
  • The for… In traverses the entire prototype chain of an object and is not recommended because of poor performance, while for… Of only traverses the current object, not the prototype chain.

The difference between Ajax, Axios, and FETCH

Ajax, a cliche, was not a new technology in itself before 2005, but rather emerged as a new term to describe a ‘new’ approach to using a collection of existing technologies, including: HTML or XHTML, CSS, JavaScript, DOM, XML, XSLT, and most importantly XMLHttpRequest. With the AJAX model, web applications can quickly render incremental updates to the user interface without reloading (refreshing) the entire page. This allows the program to respond more quickly to user actions.

However, ajax has not been a standard packaging body, like jquery ajax packaging is very convenient and easy to use, but there are still some drawbacks:

  • Itself is targeted at MVC programming, not in line with the tide of front-end MVVM
  • Based on native XHR development, the architecture of XHR itself is unclear
  • It does not conform to the principle of Separation of Concerns
  • Configuration and invocation are messy, and the event-based asynchronous model is unfriendly.

Fetch proposed by EA6 is designed to provide an interface to obtain resources (including cross-domain request), providing a more powerful and flexible function set. But at present most browsers are still in the experimental stage, the application degree is not high.

Fetch brings the following benefits:

  • Syntax concise, more semantic
  • Support async/await based on standard Promise implementation
  • More low-level, rich API (request, response)
  • XHR is a new implementation in the ES specification

Axios is a JS library, which is an HTTP client packaged based on Promise. It supports both browser side and Node side, conforms to the latest ES specification, encapsulates some conventional request and response API, and is a substitute for jquery Ajax. The bottom layer is still XMLHttpRequest object. Official website: www.axios-js.com/.

In summary, Ajax is a collection of technologies that, due to the unfriendly design of XMLHttpRequest itself, make web request initiation and data processing more cumbersome. Later, Juqery Ajax encapsulated a more practical version, but due to the demise of jquery and the advent of Promise, The EMERGENCE of HTTP request libraries like Axios makes it more convenient to initiate asynchronous requests. Fetch is an Ajax encapsulation API officially proposed by ES6, which is also based on Promise, but abandons THE XMLHttpRequest object, and uses newer specifications with simpler syntax. The downside is that most browsers are still experimental, and most don’t support the Fetch API yet.

Reference:

  • ajax – MDN

  • Fetch API – MDN

  • The difference between Ajax and Axios and FETCH

What are the traversal methods for arrays, and what are the differences

methods Change the original array The characteristics of
forEach() no Do not change the original array, no return value
map() no Generates a new array by iterating over the return value without changing the original array
filter() no Filter array, which returns an array of elements that match the criteria
for… of no for… Iterator: Iterator: Iterator: Iterator: Iterator: Iterator: Iterator: Iterator: Iterator: Iterator: Iterator: Iterator: Iterator: Iterator: Iterator
Every () and some () no Some () returns true as long as one of the elements is true; Every () returns false as long as one of them is false.
The find () and findIndex () no The array element lookup method, find(), returns the first qualified value; FindIndex () returns the index of the value of the first return condition
Reduce () and reduceRight () no Receive a function asaccumulator, and each value in the array (from left to right) begins to shrink and eventually evaluates to a single value. Reduce () operates on arrays in positive order; ReduceRight () inverts the array

What’s the difference between template and JSX

For the Runtime, just make sure the component has the Render function, and with precompilation, just make sure the render function is generated during the build. Vue files are compiled using vue-loader in Webpack. The uE-template-compiler module, which is internally dependent, precompiles the template into the render function during Webpack building. Like React, after adding JSX’s syntax sugar parser babel-plugin-transform-vue-jsx, you can write the render function directly.

So, both Template and JSX are renderings of render, except that JSX has more flexibility and advantages in complex components than Template, which is a bit dull. Template, however, is much simpler, more intuitive, and more maintainable because of its code structure, which is more consistent with the separation of view and logic.

How can I solve the problem that the VUE initialization page flashes

In vUE development, before vUE initialization, div is not under the control of VUE, so we write code without parsing will be prone to screen failure, see words like {{message}}, although this is usually a short time, but it is necessary to solve this problem.

We can add code to the CSS to hide elements until they are initialized:

[v-cloak] {    display: none; }Copy the code

If the problem is not completely resolved, add style=”display: none;” to the root element. :style=”{display: ‘block’}”

What does Extend do

This API is rarely used, extending the component to generate a constructor, and is usually used with $mount. Using the base Vue constructor, create a “subclass.” The parameter is an object that contains component options. The data option is a special case, note – it must be a function in vue.extend ().

// Create a constructor
var Profile = Vue.extend({
  template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>'.data: function () {
    return {
      firstName: 'Walter'.lastName: 'White'.alias: 'Heisenberg'}}})// Create a Profile instance and mount it to an element.
new Profile().$mount('#mount-point')
Copy the code

Separate numbers by commas in thousandths

There are many ways to implement it. Here is one of them:

/** * Splits a number into fragments * with a delimiter@param {number} Number number *@param {number} SliceLen fragment length *@param {string} The split separator *@returns string 
 */
function numberFormat(number, sliceLen, split) {
    if(sliceLen <= 0 || isNaN(sliceLen))  {
        sliceLen = 1;
    }
    const numberStr = number.toString();
    const len = numberStr.length;
    if(len <= sliceLen) {
        return numberStr;
    }
    if(typeofsplit ! = ='string') {
        split = ', ';
    }
    let str = ' ', count = 0;
    for(let i = 0; i < len; i++) {
        str += numberStr[i];
        if(count === sliceLen - 1&& i ! = len -1) {
            str += split;
            count = 0;
        } else{ count++; }}return str;
}
Copy the code

Realize the addition of non-negative large integers

MAX_SAFE_INTEGER (2^ 52-1), or if the decimal is less than the minimum Number.EPSILON (2^ -52), the calculation between numbers is not accurate.

Therefore, ES6 proposed BigInt to store these integers beyond the range, and then realize the calculation of large integers. We don’t use BigInt to add large integers. The way to do that is to simulate the rules of addition, starting with the ones place, adding the ones place, adding the ones place, and finally getting the answer.

/** * non-negative large integers add *@param {string} n1Str 
 * @param {string} n2Str 
 */
function addBignumber(n1Str, n2Str) {
  const len1 = n1Str.length;
  const len2 = n2Str.length;
  let i = 1; // 1 represents the ones digit
  let temp = 0; / / carry value
  let res = ' ';
  while(! ((i > len1 || i > len2) && temp ==0)) {
    const a = +(n1Str[len1 - i] || 0);
    const b = +(n2Str[len2 - i] || 0);
    const sum = (a + b + temp).toString();
    res = sum.slice(-1) + res;
    temp = parseInt(sum.slice(0, sum.length - 1) | |'0');
    i++;
  }
  if(i <= len1) {
    res = n1Str.slice(0, len1 - i + 1) + res;
  } else if(i <= len2) {
    res = n2Str.slice(0, len2 - i + 1) + res;
  }
  return res;
}
Copy the code

Add (1)(2)(3) equals add(1, 2)(3)

The purpose of this problem is to implement a Currization function. We’ve written about this in the previous exercise.

/** ** The Currization function *@param {Function} fn 
 * @param  {... any} args 
 */
function curry(fn, ... args) {
  if(fn.length <= args.length) {
    return fn.apply(this, args);
  }
  return curry.bind(this, fn, ... args); }/** ** sum of three numbers */
function add(a, b, c) {
  debugger
  return a + b + c;
}

const curryAdd = curry(add);

console.log(curryAdd(1) (2) (3) === curryAdd(1.2) (3))
Copy the code

Code output (Promise related)

Code snippet:

console.log('1');

setTimeout(function() {
    console.log('2');
    process.nextTick(function() {
        console.log('3');
    })
    new Promise(function(resolve) {
        console.log('4');
        resolve();
    }).then(function() {
        console.log('5')
    })
})
process.nextTick(function() {
    console.log('6');
})
new Promise(function(resolve) {
    console.log('7');
    resolve();
}).then(function() {
    console.log('8')})setTimeout(function() {
    console.log('9');
    process.nextTick(function() {
        console.log('10');
    })
    new Promise(function(resolve) {
        console.log('11');
        resolve();
    }).then(function() {
        console.log('12')})})Copy the code

NextTick is the API in Node.js. In Node, code is executed in the same way as on the browser side, where macro and microtasks are executed alternately, with asynchronous queues of macro and microtasks.

The node side is the same, and its event loop mechanism is divided into the following stages:

  • The timer: This phase has been executedsetTimeout()setInterval()The scheduling callback function of.
  • Pending callback: An I/O callback that is deferred until the next iteration of the loop.
  • Idle, prepare: used only in the system.
  • polling: Retrieves new I/O events; Perform I/ O-related callbacks (in almost all cases, except for closed callback functions, those made by timers andsetImmediate()Out of schedule), the rest of the case node will block at this point in due course.
  • detection:setImmediate()This is where the callback function is executed.
  • The closed callback function: Some closed callback functions such as:socket.on('close', ...).

If you are confused, please refer to nexttick-node. js. In fact, it is the same as macro and micro tasks on the browser side.

SetImmediate (), on the other hand, is similar to setTimeout(), but does behave differently depending on the timing of the call.

  • setImmediate()Designed once in the presentpollingWhen the phase is complete, the script is executed.
  • setTimeout()Run the script after the minimum threshold in ms.

As far as the user is concerned, we have two similar calls, but their names are confusing.

  • process.nextTick()Execute immediately at the same stage.
  • setImmediate()Fired on the next iteration or ‘tick’ of the event loop.

Essentially, the two names should be swapped because process.nexttick () triggers faster than setImmediate(), but this is a hangover from the past and therefore unlikely to change. A rash name swap would break most packages on NPM. More modules are being added every day, which means we have to wait every day for more potential damage to happen. As confusing as these names are, they don’t change.

Based on the API analysis above, let’s look at the execution flow analysis of specific code snippets:

console.log('1'); // 1

// 2. Timer (can be read as asynchronous macro task queue)
setTimeout(function() {
    // print 2
    console.log('2');
    // 11. Add the immediate phase to execute the callback
    process.nextTick(function() {
        Print 3 to perform the next stage: microtask
        console.log('3');
    })
    // 12. Implement Promise
    new Promise(function(resolve) {
        // print 4
        console.log('4');
        // 14. The asynchronous microtask enters the queue and executes the nextTick phase
        resolve();
    }).then(function() {
        Print 5 to execute the next macro task
        console.log('5')})})// 3. Add the immediate phase to execute the callback
process.nextTick(function() {
    // print 6. After one poll execution ends, setImmediate executes and opens the next event poll: execute the microtask queue
    console.log('6');
})
// 4. Implement asynchronous Promise
new Promise(function(resolve) {
    // 5. print 7
    console.log('7');
    // 6. The asynchronous microtask is queued
    resolve();
}).then(function() {
    Print 8 to execute the macro task queue
    console.log('8')})// 7. Timer (asynchronous macro task enters queue), the execution of one phase ends, and nextTick is executed
setTimeout(function() {
    // print 9
    console.log('9');
    // 18. Add the immediate phase to execute the callback
    process.nextTick(function() {
        Print 10, nextTick completes, and the next phase starts: executing the microtask queue
        console.log('10');
    })
    // implement the Promise
    new Promise(function(resolve) {
        // print 11
        console.log('11');
        // 21. The asynchronous microtask enters the queue, the macro task finishes, and the callback function nextTick is executed
        resolve();
    }).then(function() {
        // print 12
        console.log('12')})})Copy the code

Collect the print information and the execution sequence to get the output (for this type of long code, the executed code can be commented out to make it clear) :

1
7 
6 
8 
2 
4 
3 
5 
9 
11
10
12
Copy the code

Reference:

  • Window.setImmediate() – MDN
  • nexttick – node.js

Code snippet:


console.log(1)

setTimeout(() = > {
  console.log(2)})new Promise(resolve= >  {
  console.log(3)
  resolve(4)
}).then(d= > console.log(d))

setTimeout(() = > {
  console.log(5)
  new Promise(resolve= >  {
    resolve(6)
  }).then(d= > console.log(d))
})

setTimeout(() = > {
  console.log(7)})console.log(8)
Copy the code

Perform process analysis:

// 1
console.log(1)

// 2. Join the asynchronous macro task queue 01
setTimeout(() = > {
  Print 2, execute microtask queue (none), continue to execute macro task queue 02
  console.log(2)})// 3. Implement the Promise
new Promise(resolve= >  {
  // 4
  console.log(3)
  // 5. Join the asynchronous microtask queue
  resolve(4)
}).then(d= > console.log(d)) // 9. Print 4, the execution of microtask queue is complete, and execute macro task queue 01

// 6. Join the asynchronous macro task queue 02
setTimeout(() = > {
  // 11. Print 5
  console.log(5)
  // 12. Implement Promise
  new Promise(resolve= >  {
    // 13. Join the asynchronous microtask queue. After the macro task execution is complete, the next microtask queue is executed
    resolve(6)
  }).then(d= > console.log(d)) Print 6 and execute the next macro task queue 03
})

// 7. Join the asynchronous macro task queue 03
setTimeout(() = > {
  // print 7
  console.log(7)})// 8. Print 8, the macro task is complete, and the microtask queue is executed
console.log(8)
Copy the code

Print result:

1
3
8
4
2
5
6
7
Copy the code

Code snippet:

setTimeout(() = > {
  console.log(1);
}, 0);

new Promise((resolve, reject) = > {
  console.log(2);
  resolve(3);
  new Promise(resolve2= > {
    console.log(4);
    resolve2(5);
  }).then((r) = > {
    console.log(r);
  });
}).then(r= > {
  console.log(r);
});

new Promise(resolve2= > {
  console.log(6);
  resolve2(7);
}).then((r) = > {
  console.log(r);
});
Copy the code

The Promise callback inside the Promise will enter the asynchronous microtask queue before the parent Promie, so the final output is:

2
4
6
5
3
7
1
Copy the code