30 days

Grass grid official website implementation (Swiper rotation map plug-in, Gitee upload website)

Szcodeman. Gitee. IO/daily – demo /…

Web answer small program

Szcodeman.gize. IO /daily-demo/…

Thirty-one day

ES6 in relation to ECMAScript 2015

ES6 is both a historical term and a general reference, meaning the next generation of JavaScript standard after 5.1 version, covering ES2015, ES2016, ES2017, etc., and ES2015 is the official name, especially refers to the official version of the language standard released in that year. References to ES6 in this book generally refer to the ES2015 standard, but sometimes also refer to the “next generation JavaScript language.”

Babel transcoder

Babel is a widely used ES6 transcoder that converts ES6 code into ES5 code for execution in older browsers. This means that you can write in ES6 style without worrying about whether your current environment will support it. Here’s an example.

Input. map(item => item + 1); Input. map(function (item) {return item + 1; });Copy the code

The original code above uses the arrow function, which Babel turns into a normal function that can be executed in JavaScript environments that do not support arrow functions.

The following command installs Babel in the project directory.

$ npm install --save-dev @babel/core
Copy the code

1. Let and const

Like var, let and const are used to declare variables;

// const declares a read-only constant. Once declared, the value of a constant cannot be changed. // Const guarantees that the value of the variable is not changed, but that the memory address to which the variable points is stored is not changed. Const PI = 3.1415; PI = 3; // TypeError: Assignment to constant variable.Copy the code

Let is different from var

A counter for a loop is suitable for the let command.

for (let i = 0; i < 10; i++) { // ... } console.log(i); // ReferenceError: I is not defined // let declare that the variable is I in the block level scope, the external reference is not defined, for each I in the body of the loop is independent of its scope I for (var I = 0; i < 10; i++) { // ... } console.log(i); // 10 // var is the variable declared in the global scope of I. Every application changes the global I, so the I in the for loop is the same ICopy the code
There is no variable promotion

The “variable promotion” phenomenon occurs when the var command is used, that is, the variable can be used before the declaration and its value is undefined.

To correct this, the let command changes the syntactic behavior so that the variable it declares must be used after the declaration or an error will be reported.

// var case console.log(foo); Var foo = 2; // let's case console.log(bar); // ReferenceError let bar = 2;Copy the code
Temporary dead zone

As long as the let command exists in the block-level scope, the variables it declares are “binding” to the region, no longer subject to external influence.

var tmp = 123;
​
if (true) {
  tmp = 'abc'; // ReferenceError
  let tmp;
}
Copy the code

ES6 explicitly states that if there are let and const commands in a block, the variables declared by the block to those commands form a closed scope from the start. Any time these variables are used before declaration, an error is reported.

2. GlobalThis object

The JavaScript language has a top-level object that provides the global environment (that is, the global scope) in which all code runs. However, top-level objects are not uniform across implementations.

  • In the browser, the top-level object iswindow, but Node and Web workers do notwindow.
  • In browsers and Web workers,selfAlso points to top-level objects, but Node doesn’tself.
  • In Node, the top-level object isglobal, but no other environment supports it.

In order for the same code to be able to fetch top-level objects in any environment, it is now common to use the this keyword, but there are limitations.

ES2020 introduces globalThis as a top-level object at the level of language standards. That is, globalThis exists in any context and can be retrieved from it to point to the top-level object pointing to this in the global context.

The shim library global-This emulates this proposal and is available in all environments.

3. Deconstructive assignment of variables

ES6 allows you to extract values from arrays and objects and assign values to variables in a pattern known as deconstruction

3.1 Deconstruction and assignment of data

Previously, to assign a value to a variable, you had to specify a value directly.

let a = 1;
let b = 2;
let c = 3;
let [foo] = [];
Copy the code

ES6 allows the following to be written; If the deconstruction fails, the value of the variable is equal to undefined.

let [a, b, c] = [1, 2, 3];
// a: 1, b: 2, c: 3
let [bar, foo] = [1];
// foo: undefined
let [q, [w], e] = [1, [2, 3], 4];
// q: 1, w: 2, e: 4 
Copy the code

If the right-hand side of the equals sign is not an array (or, more strictly, not a traversable structure, see the chapter On Iterator), then an error is reported.

// let [foo] = 1; let [foo] = false; let [foo] = NaN; let [foo] = undefined; let [foo] = null; let [foo] = {};Copy the code
The default value

Destruct assignment allows you to specify default values.

let [foo = true] = []; foo // truelet [x, y = 'b'] = ['a']; // x='a', y='b' => let [x, y = 'b'] = ['a', undefined]; // x='a', y='b'Copy the code

Note that ES6 uses the strict equality operator internally (= = =) to determine whether a position has a value. So, only if an array member is strictly equal toundefined, the default value takes effect.

The default value can refer to another variable of the deconstructed assignment, but that variable must already be declared.

let [x = 1, y = x] = [];     
// x=1; y=1 let [x = 1, y = x] = [2];    
// x=2; y=2 let [x = 1, y = x] = [1, 2]; 
// x=1; y=2 let [x = y, y = 1] = [];    
// ReferenceError: y is not defined
Copy the code

3.2 Object deconstruction assignment

let { foo, bar } = { foo: 'aaa', bar: 'bbb' }; foo // "aaa"bar // "bbb"Copy the code

Object deconstruction differs from arrays in one important way. The elements of an array are arranged in order,

The value of a variable depends on its position; The attributes of an object have no order, and variables must have the same name as the attributes to get the correct value.

Attribute name is incorrect or does not exist, can not get the value

let {bar: bar, foo: foo} = { foo: 'aaa', bar: 'bbb' }; Let {bar, foo} = {foo: 'aaa', bar: 'BBB'}; let {bar, foo} = {foo: 'aaa', bar: 'BBB'}; foo // "aaa"bar // "bbb" let { baz } = { foo: 'aaa', bar: 'bbb' }; baz // undefined let {foo} = {bar: 'baz'}; foo // undefinedCopy the code

Deconstruction can also be used to nest structured objects.

let obj = { p: [ 'Hello', { y: 'World' } ]}; let { p: [x, { y }] } = obj; X // "Hello"y // "World" // Note that p is a mode, not a variable, and therefore will not be assigned. If p is also assigned as a variable, it can be written as follows.Copy the code
let obj = { p: [ 'Hello', { y: 'World' } ]}; let { p, p: [x, { y }] } = obj; x // "Hello"y const node = { loc: { start: { line: 1, column: 5 } }}; let { loc, loc: { start }, loc: { start: { line }} } = node; Line // 1loc // Object {start: Object}start // Object {line: 1, column: 5} // Only line is the variableCopy the code

The default value

The deconstruction of an object can also specify default values.

var {x = 3} = {};
x // 3
var {x, y = 5} = {x: 1};
x // 1
y // 5
var {x: y = 3} = {};
y // 3
var {x: y = 3} = {x: 5};
y // 5
var { message: msg = 'Something went wrong' } = {};
msg // "Something went wrong"
Copy the code

The default value is valid only if the object’s attribute value is strictly equal toundefined.

var {x = 3} = {x: undefined};
x // 3
var {x = 3} = {x: null};
x // null
Copy the code

In the code above, the attribute x is null, and since null is not exactly equal to undefined, it is a valid assignment, causing the default value 3 not to take effect.

3.3 Deconstructing the assignment rules

The rule for deconstructing assignment is to turn the value to the right of the equals sign into an object whenever it is not an object or array. Undefined and NULL cannot be converted to objects, so destructuring assignments to them will result in an error.

let { prop: x } = undefined; // TypeErrorlet { prop: y } = null; // TypeError
Copy the code
let {toString: s} = 123;
s === Number.prototype.toString 
// true
let {toString: s} = true;
s === Boolean.prototype.toString // true
Copy the code

3.4 Deconstructive assignment of function parameters

Function arguments can also be destructively assigned.

function add([x, y]){ return x + y; } add([1, 2]); / / 3Copy the code

In the above code, the arguments to the function add are ostensibly an array, but the moment they are passed in, the array arguments are resolved to form variables X and y. For the code inside the function, the arguments it senses are x and y.

Function arguments can also be destructed using default values.

function move({x = 0, y = 0} = {}) { return [x, y]; } move({x: 3, y: 8}); // [3, 8] move({x: 3}); // [3, 0] move({}); // [0, 0] move(); / / [0, 0]Copy the code

The move function takes an object, which is deconstructed to get the values of the variables x and y. If deconstruction fails, x and y are equal to the default values.

3.5 Parenthesis problem

Parentheses are not allowed for the following three deconstruction assignments

  1. Variable declaration statement

    // let [(a)] = [1]; let {x: (c)} = {}; let ({x: c}) = {}; let {(x: c)} = {}; let {(x): c} = {}; let { o: ({ p: p }) } = { o: { p: 2 } };Copy the code
  2. Function parameters

    Function arguments are also variable declarations and therefore cannot have parentheses.

    Function f([(z)]) {return z; Function f([z,(x)]) {return x; }Copy the code
  3. The mode of the assignment statement

    {p: a}) = {p: 42}; ([a]) = [5];Copy the code
    [({p: a}), {x: c}] = [{}, {}];Copy the code

A case where parentheses can be used

There is only one case in which parentheses can be used: for the non-schema part of an assignment statement, parentheses can be used.

[(b)] = [3]; {p: (d)} = {}); // Correct [(parseint.prop)] = [3]; / / rightCopy the code

3.4 Application of deconstruction assignment

  1. Swap the values of variables

    let x = 1; let y = 2; [x, y] = [y, x];Copy the code
  2. Function returns multiple values

    Function example() {return [1, 2, 3]; } let [a, b, c] = example(); Function example() {return {foo: 1, bar: 2}; } let { foo, bar } = example();Copy the code
  3. Definition of function parameters

    Function f([x, y, z]) {function f([x, y, z]) {... } f([1, 2, 3]); Function f({x, y, z}) {... function f({x, y, z}) {... } f({z: 3, y: 2, x: 1});Copy the code
  4. Extracting JSON data

    let jsonData = { id: 42, status: "OK", data: [867, 5309] }; let { id, status, data: number } = jsonData; console.log(id, status, number); // 42, "OK", [867, 5309]Copy the code
  5. Default values for function arguments

    jQuery.ajax = function (
        url, {  
        async = true,  
        beforeSend = function () {},  
        cache = true,  
        complete = function () {},  
        crossDomain = false,  
        global = true, 
        // ... more config} = {}
        ) {  
        // ... do stuff
    };
    Copy the code
  6. Traverse the Map structure

    const map = new Map(); map.set('first', 'hello'); map.set('second', 'world'); for (let [key, value] of map) { console.log(key + " is " + value); } // first is hello // second is worldCopy the code
  7. Specifies the method of input module

    import { Input, Button, List } from "antd"
    Copy the code

Thirty-second day

1. String extension

Unicode representation of 1.1 characters

ES6 has enhanced Unicode support, allowing a character to be represented in the \uxxxx form, where XXXX represents the Unicode code point of the character.

"\u0061"
// "a"
Copy the code

This representation is limited to characters with code points between \u0000 and \uFFFF. Characters outside this range must be represented as two double bytes. With this notation, there are six ways that JavaScript can represent a character.

'\z' === 'z'  // true
'\172' === 'z' // true
'\x7A' === 'z' // true
'\u007A' === 'z' // true
'\u{7A}' === 'z' // true
Copy the code

1.2 String traversal

ES6 adds a traverser interface to strings, making them available for… The of loop traverses.

for (let codePoint of 'foo') {
  console.log(codePoint)
}
// "f"
// "o"
// "o"
Copy the code

Besides traversing strings, the greatest advantage of this traverser is that it can recognize code points larger than 0xFFFF, which traditional for loops cannot recognize.

let text = String.fromCodePoint(0x20BB7); for (let i = 0; i < text.length; i++) { console.log(text[i]); } // " " // " " for (let i of text) { console.log(i); } / / "𠮷"Copy the code

1.3 Template Strings

In traditional JavaScript languages, output templates are written like this (jQuery’s approach is used below).

$('#result').append(
  'There are <b>' + basket.count + '</b> ' +
  'items in your basket, ' +
  '<em>' + basket.onSale +
  '</em> are on sale!'
);
Copy the code

This is rather cumbersome, and ES6 has introduced template strings to solve this problem.

$('#result').append(`
  There are <b>${basket.count}</b> items
   in your basket, <em>${basket.onSale}</em>
  are on sale!
`);
Copy the code

Template strings are enhanced strings, identified by backquotes (‘). It can be used as a regular string, it can be used to define multi-line strings, or it can be used to embed variables in strings.

Represents a multi-line string, with all whitespace and indentation retained in the output

A variable is embedded in the template string. You need to write the variable name in ${}.

1.4 Tag (function) templates

Template strings do more than that. It can be followed by the name of a function that will be called to process the template string. This is called the “tag template” feature.

Alert 'hello' // equivalent to alert(['hello'])Copy the code

If there are variables in the template character, the call is not simple. Instead, the template string is processed into multiple arguments before the function is called. The label before the template string is the function name

let a = 5; let b = 10; tag`Hello ${ a + b } world ${ a * b }`; // Equivalent to tag(['Hello ', 'world ', ''], 15, 50);Copy the code

1.5 New String methods

1.5.1 String. Raw ()

ES6 provides a raw() method for native Strings. This method returns a string in which all slashes have been escaped (that is, a slash followed by another slash), often used in template string processing.

String.raw`Hi\n${2+3}! '// Actually returns "Hi\n5!" , displays the escaped result "Hi\n5!" String.raw`Hi\u000A! `; // Actually returns "Hi\u000A!" , displays the escaped result "Hi\u000A!"Copy the code

If the slash of the original String has been escaped, string.raw () is escaped again.

1.5.2 includes (), startsWith (), endsWith ()

Traditionally, JavaScript has only had the indexOf method, which can be used to determine whether one string is contained within another. ES6 offers three new approaches.

  • Includes () : Returns a Boolean value indicating whether the parameter string was found.
  • StartsWith () : Returns a Boolean value indicating whether the argument string is at the head of the original string.
  • EndsWith () : Returns a Boolean value indicating whether the argument string is at the end of the original string
1.5.3 repeat ()

The repeat method returns a new string, repeating the original string n times.

'x'.repeat(3) // "xxx"
'hello'.repeat(2) // "hellohello"
'na'.repeat(0) // ""
Copy the code

The argument is rounded if it is a decimal.

'na'. Repeat (2.9) / / "nana"Copy the code

If the repeat argument is negative or Infinity, an error is reported. The NaN argument is equal to 0.

If the argument of the repeat is a string, it is converted to a number first

1.5.4 trimStart (), trimEnd ()

ES2019 adds the trimStart() and trimEnd() methods for string instances. They behave in the same way as trim(), with trimStart() eliminating whitespace at the head of the string and trimEnd() eliminating whitespace at the end. They all return a new string and do not modify the original string.

const s = '  abc  ';
​
s.trim() // "abc"
s.trimStart() // "abc  "
s.trimEnd() // "  abc"
Copy the code

In the code above, trimStart() removes only the header whitespace and preserves the trailing whitespace. TrimEnd () behaves similarly.

1.5.5 replaceAll ()

The string instance method replace() can only replace the first match.

'aabbcc'.replace('b', '_')// 'aa_bcc'
​
'aabbcc'.replaceAll('b', '_')// 'aa__cc'
Copy the code

2. Regular extensions

2.1 RegExp constructor

In the first case, the argument is a string, in which case the second argument represents the regular expression modifier (flag).

var regex = new RegExp('xyz', 'i'); Var regex = /xyz/ I;Copy the code

In the second case, if the argument is a regular expression, a copy of the original regular expression is returned.

var regex = new RegExp(/xyz/i); Var regex1 = /xyz/ I; console.log(regex == regex1); // falseCopy the code

3. Numerical expansion

3.1 Binary and octal notation

ES6 provides a new way to write binary and octal values, represented by prefixes 0b (or 0b) and 0O (or 0O), respectively.

0b111110111 === 503 // true
0o767 === 503 // true
Copy the code

If you want to decimal string values prefixed with 0b and 0o, use the Number method.

Number('0b111')  // 7
Number('0o10')  // 8
Copy the code

3.2 Numerical separators

ES2021, which allows JavaScript numeric values to be delimited by an underscore (_).

let budget = 1_000_000_000_000;
budget === 10 ** 12 // true
Copy the code

This numeric separator does not have a specified interval of digits, that is, you can add one separator every three digits, or one separator every one, every two, and every four digits.

123_00 === 12_300 // true
​
12345_00 === 123_4500 // true
12345_00 === 1_234_500 // true
Copy the code

Decimal and scientific notation can also use numeric separators.

// Decimal 0.000_001 // scientific counting 1e10_000Copy the code

There are several considerations for using numeric separators.

  • It cannot be leading or trailing in a value.
  • Two or more delimiters cannot be joined together.
  • There can be no separators before and after the decimal point.
  • In scientific notation, representing exponentseorEThere can be no delimiters before and after.

3.3 Number. IsFinite (), Number. The isNaN ()

ES6 provides two new methods on Number objects, number.isfinite () and number.isnan ().

Number.isfinite () is used to check whether a Number isFinite, i.e., not Infinity.

Number.isFinite(15); / / true Number. IsFinite (0.8); // true Number.isFinite(NaN); // false Number.isFinite(Infinity); // false Number.isFinite(-Infinity); // false Number.isFinite('foo'); // false Number.isFinite('15'); // false Number.isFinite(true); // falseCopy the code

Number.isnan () is used to check whether a value isNaN.

Number.isNaN(NaN) // true
Number.isNaN(15) // false
Number.isNaN('15') // false
Number.isNaN(true) // false
Number.isNaN(9/NaN) // true
Number.isNaN('true' / 0) // true
Number.isNaN('true' / 'true') // true
Copy the code

If the parameter type is not NaN, number. isNaN always returns false.

3.4 Extension of the Math object

ES6 adds 17 new math-related methods to the Math object. All of these methods are static and can only be called on Math objects.

3.4.1 track math.h trunc ()

The math. trunc method is used to remove the fractional part of a number and return the integer part.

Math. Trunc (4.1) / / 4 math.h trunc (4.9) / / 4 math.h trunc (4.1) / / - 4 math.h trunc (4.9) / / - 4 math.h trunc (0.1234) / / 0Copy the code

For non-numeric values, math.trunc internally converts them to numeric values using the Number method.

NaN is returned for null values and values that cannot intercept integers.

3.4.2 math.h sign ()

The math. sign method is used to determine whether a number is positive, negative, or zero. For non-numeric values, they are converted to numeric values first. It returns five values.

  • Returns if the argument is a positive number+ 1;
  • If argument is negative, return- 1;
  • Argument 0, returns0;
  • Argument -0, returns0;
  • Other values, returnNaN.
Math.sign(-5) // -1
Math.sign(5) // +1
Math.sign(0) // +0
Math.sign(-0) // -0
Math.sign(NaN) // NaN
Copy the code

If the parameter is not a value, it is automatically converted to a value. NaN is returned for values that cannot be converted to numeric values.

Rule 3.4.3 math.h hypot ()

The math.hypot method returns the square root of the sum of squares of all parameters.

Math.hypot(3, 4); // 5 Pythagorean theoremCopy the code

4. BigInt Data type

Math.pow(2, 53) === = math.pow (2, 53) + 1 // true // For numbers greater than 2 to the power of 1024, Cannot express math.pow (2, 1024) // InfinityCopy the code

ES2020 addresses this problem by introducing a new data type, BigInt (large integer), which is ECMAScript’s eighth data type. BigInt is only used to represent integers. There is no limit on the number of digits.

const a = 2172141653n; const b = 15346349309n; // BigInt can keep the precision a * b // 333344445566667777n // Common integers cannot keep the precision Number(a) * Number(b) // 33334444555566670000Copy the code

To distinguish BigInt from Number, data of type BigInt must be suffixed with n.

1234 // Common integer 1234N // BigInt // BigInt operation 1n + 2n // 3nCopy the code

BigInt can also be represented in a variety of bases, all with the suffix n.

BigInt and plain integers are two different values, and they are not equal.

42n === 42 // false
Copy the code

Typeof operator returns BigInt for data of type BigInt.

typeof 123n // 'bigint'
Copy the code

4. Function extension

4.1 Positions of default Parameter Values

In general, the parameter that defines the default value should be the last parameter of the function. Because it’s easier to see what parameters are being omitted. If non-trailing arguments are set to default values, they cannot be omitted.

Function f(x = 1, y) {return [x, y]; } f () / / [1, undefined] f (2) / / [2, undefined] f (1) / / an error f (undefined, 1) / / [1, 1] / / the function f (x, y = 5, z) { return [x, y, z]; } f () / / / undefined ", undefined, 5 f (1) / / [1, 5, undefined] f (1, 2) / / an error f (1, undefined, 2) / / [1, 5, Function f(x, z, y=5) {return [x, y, z]; } f() // [undefined, 5, undefined] f(1) // [1, 5,undefined] f(1, 2) // [1, 5, 2] f(1, 2, 3) // [1, 3, 2]Copy the code

None of the arguments with default values in the code above are tail arguments. In this case, you cannot omit this parameter without the argument that follows it, unless you explicitly enter undefined.

4.2 Function Length attribute

When a default value is specified, the length property of the function returns the number of arguments for which no default value is specified. That is, the length attribute is distorted when a default value is specified.

(function (a) {}).length // 1
(function (a = 5) {}).length // 0
(function (a, b, c = 5) {}).length // 2
​
(function (a = 0, b, c) {}).length // 0
(function (a, b = 1, c) {}).length // 1
Copy the code

4.3 scope

Once the default values of parameters are set, the parameters form a separate context when the function is declared initialized. After initialization, the scope will disappear. This syntactic behavior does not occur if the parameter defaults are not set.

var x = 1;
​
function f(x, y = x) {
  console.log(y);
}
​
f(2) // 2
​
Copy the code
let x = 1;
​
function f(y = x) {
  let x = 2;
  console.log(y);
}
​
f() // 1
Copy the code

4.4 rest parameters

ES6 introduces the REST parameter (of the form… Variable name), used to get extra arguments to a function so you don’t need to use the arguments object. The rest argument goes with a variable that puts the extra arguments into an array.

function add(... values) { let sum = 0; for (var val of values) { sum += val; } return sum; } add(2, 5, 3) // 10Copy the code

The add function is a summation function that can be passed any number of arguments using the REST argument.

4.5 Arrow Function

Basic usage

ES6 allows functions to be defined using arrows (=>).

var f = v => v; Var f = function (v) {return v; };Copy the code

If the arrow function requires no arguments or more than one argument, use a parenthesis to represent the argument part.

var f = () => 5; Var f = function () {return 5}; var sum = (num1, num2) => num1 + num2; Var sum = function(num1, num2) {return num1 + num2; };Copy the code

If the arrow function has more than one statement in its code block, enclose them in braces and return them with a return statement.

var sum = (num1, num2) => { return num1 + num2; }
Copy the code

Because braces are interpreted as blocks of code, if an arrow function returns an object directly, it must enclose braces around the object or an error will be reported.

Let getTempItem = id => {id: id, name: "Temp"}; Let getTempItem = id => ({id: id, name: "Temp"});Copy the code

The following is a special case that, while running, gets the wrong result.

let foo = () => { a: 1 }; foo() // undefinedCopy the code