ES6 core knowledge learning

Get started by simple demo, quickly master. Help you quickly use ES6 in your projects; Write more elegant code! Github

Babel (demo1.js)

Babel is a JavaScript compiler; Convert ES6 to ES5 syntax

  • Global installation uses Babel
/ / installation
npm install -g babel-cli
/ / use
babel src/demo1.js -o dist/demo1.js
Copy the code
  • Use Babel in projects (recommended)
/ / installation
yarn add @babel/cli -D
yarn add @babel/core -D
yarn add @babel/node -D
yarn add @babel/preset-env -D
yarn add core-js@3 -D

//.babelrc configuration file
{
  "presets": [["@babel/preset-env",
      {
        "useBuiltIns": "entry"."corejs": 3."debug": false}}]]// package.json Command yarn Babel :demo1
"babel:demo1": "babel src/demo1.js -o dist/demo1.js"

// Execute compiled code through Node
node dist/demo1.js
Copy the code

Declaration of ES6 (demo2.js)

  • var let const
Var global declaration let local const constant declaration is not allowed to changeCopy the code

Destruct Assignment of variables (demo3.js)

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

  • Basic usage
// Previously, to assign a value to a variable, you could only specify the value directly.
let a = 1;
let b = 2;
let c = 3;
// ES6 allows the following to be written.
let [a, b, c] = [1.2.3];
console.log(a, b, c);
Copy the code
  • Default: Destructuring assignments allows you to specify default values; If the deconstruction fails, the value of the variable equals undefined.

  • Object destructuring assignment

let { foo, bar } = { foo: 'foo'.bar: 'bar' };
Copy the code
  • Destruct assignment of a string
const [a, b, c, d, e] = 'hello';
Copy the code
  • Deconstructive assignment of values and Bores
// When destructing an assignment, if the right side of the equals sign is a value and a Boolean value, it is converted to an object first.
let { toString: s } = 123;
s === Number.prototype.toString; // true
let { toString: s } = true;
s === Boolean.prototype.toString; // true
// In the code above, both the numeric and boolean-wrapped objects have toString attributes, so the variable s can take a value.

// 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; // TypeError
let { prop: y } = null; // TypeError
Copy the code

Extended operators and REST operators (demo4.js)

  • Object extension operator (…)
function func(. arg) {
  console.log(arg[0]);
  console.log(arg[1]);
  console.log(arg[2]);
}

func(1.2.3);
Copy the code
  • rest(…) The operator
function fun2(first, ... arg) {
  console.log(arg.length);
}
fun2([1.2.3.4.5]);
Copy the code

Extension of strings (demo5.js)

  • String template
const name = 'leslie';
let welcome = ` welcome${name}The arrival of `;
console.log(welcome);

let a = 1;
let b = 2;
console.log(`result: ${a + b}`);
Copy the code
  • String lookup
Includes indexOf instead
let name2 = 'leslie';
let text = 'hi leslie';
console.log(text.indexOf(name2) > -1);
/ / equivalent to the
console.log(text.includes(name2));
Copy the code
startsWith endsWith
// startsWith endsWith start and end search
console.log(text.startsWith('hi'));
console.log(text.endsWith('lie'));
Copy the code
  • Copy string repeat
console.log('hello'.repeat(3));
Copy the code

Extension of values (demo6.js)

// Declare Binary
let binary = 0b010101;
console.log(binary); / / 21

// declare Octal in Octal
let octal = 0o666;
console.log(octal); / / 438

// isFinite is a number
let a = 11 / 4;
console.log(Number.isFinite(a));
console.log(Number.isFinite('hi'));
console.log(Number.isFinite(NaN));
console.log(Number.isFinite(undefined));

// NaN
console.log(Number.isNaN(NaN));

// number.isINTEGER () is used to determine whether a value is an integer.
console.log(Number.isInteger(10));
Number.parseInt('12.34'); / / 12
Number.parseFloat('123.45 #'); / / 123.45

// Value range number.isSafeINTEGER () Specifies whether it is a safe integer
// Minimum safe integer
Number.EPSILON === Math.pow(2, -52); // true
Number.EPSILON; / / 2.220446049250313 e-16
Number.EPSILON.toFixed(20); / / "0.00000000000000022204"

// The maximum safe integer
Number.MAX_SAFE_INTEGER === Math.pow(2.53) - 1; // true
Number.MAX_SAFE_INTEGER === 9007199254740991; // true

Number.MIN_SAFE_INTEGER === -Number.MAX_SAFE_INTEGER; // true
Number.MIN_SAFE_INTEGER === -9007199254740991; // true
Copy the code

New array for ES6 (demo7.js)

  • Array.from
// Json array format
let json = {
  0: 'Joe'.1: 'bill'.length: 2};let arr = Array.from(json);
console.log(arr);
Copy the code
  • Array.of
console.log(Array.of(3.4.5.6));
console.log(Array.of('a'.'b'));
Copy the code
  • Find () and findIndex() of array instances
let arr3 = [1.2.3];
console.log(arr3.find((n) = > n < 2));
console.log(arr3.findIndex((n) = > n < 2));
Copy the code
  • Fill () for array instances
['a'.'b'.'c'].fill(7); / / (7, 7, 7)
new Array(3).fill(7); / / (7, 7, 7)
Copy the code
  • Array instance entries(), keys() and values()
for (let index of ['a'.'b'].keys()) {
  console.log(index);
}
/ / 0
/ / 1

for (let elem of ['a'.'b'].values()) {
  console.log(elem);
}
// 'a'
// 'b'

for (let [index, elem] of ['a'.'b'].entries()) {
  console.log(index, elem);
}
// 0 "a"
// 1 "b"
Copy the code
  • Includes () of array instances
[1.2.3].includes(2); // true
[(1.2.3)].includes(4); // false
[(1.2.NaN)].includes(NaN); // true
Copy the code
  • Array instance flat(), the members of the flatMap() Array are sometimes still arrays, array.prototype.flat () is used to “flatten” nested arrays into one-dimensional arrays. This method returns a new array with no effect on the original data.
// Flatten one layer by default
[1.2[3.4]].flat(); // [1, 2, 3, 4]

[1.2[3[4.5]]].flat(); // [1, 2, 3, [4, 5]]

[1.2[3[4.5]]].flat(2); // [1, 2, 3, 4, 5]

// Convert an arbitrary dimensional array to a one-dimensional array
[1[2[3]]].flat(Infinity); / / [1, 2, 3]
Copy the code

Arrow functions and extensions (demo8.js)

  • Strict mode ES2016 has changed a bit, stating that functions cannot be explicitly set to strict mode internally if they use default values, destructed assignments, or extended operators. Otherwise, an error will be reported.
  • Arrow function
const add = (a, b) = > {
  return a + b;
};
Copy the code

Functions and arrays in ES6 (demo9.js)

  • Object function deconstruction
let json = {
  a: 'Joe'.b: 'bill'};function func({ a, b = 'hi' }) {
  console.log(a, b);
}
func(json);
Copy the code
  • An array of deconstruction
let arr = ['a'.'b'];
function func2(a, b) {
  console.log(a, b); } func2(... arr);Copy the code
  • In the use of the
let obj = {
  a: 'Joe'.b: 'bill'};console.log('c' in obj); // false

let arr2 = ['a',,,];console.log(0 in arr2); // true
console.log(1 in arr2); // false
Copy the code
  • Array traversal
let arr3 = ['a'.'b'.'c'];
arr3.forEach((val, index) = > {
  console.log(index, val);
});

arr3.filter((x) = > console.log(x));

arr3.some((x) = > console.log(x));

let newArr = arr3.map((x) = > (x = 'web'));
console.log(newArr);
Copy the code
  • Array to string
console.log(arr3.toString());
console.log(arr3.join('|'));
Copy the code

Object extension (demo10.js)

// Attributes are expressed more succinctly
let max = 'big';
let min = 'small';
let obj = { max, min }; // let obj = {Max: Max, min: min}
console.log(obj);

// Build the key value
let key = 'skill';
var obj2 = {
  [key]: 'web'};console.log(obj2);

// Custom object methods
let obj3 = {
  add: function (a, b) {
    returna + b; }};console.log(obj3.add(1.2));

/** ** === identical * is() strictly equal */
let a = { name: 'leslie' };
let b = { name: 'leslie' };
let c = Object.is(a, b); // equivalent to a.name === b.name
console.log(c); // false

console.log(+0= = = -0); // true
console.log(NaN= = =NaN); // false

Object.is(+0, -0); // false
Object.is(NaN.NaN); // true

// Merge object.assign
let d = { name: 'hi' };
let e = { age: 18 };
let f = { sex: 'male' };
let g = Object.assign(d, e, f);
console.log(g);
Copy the code

Symbol – New data type (demo11.js)

/** * Value types: String, Number, Boolean, Null, Undefined, Symbol. * Reference data types: Object, Array, Function. * /

// Add a new data type
let f = Symbol(a);console.log(typeof f);

let my = Symbol('my');
console.log(my);
console.log(my.toString());

// Apply to objects
let b = Symbol(a);let c = {
  [b]: 'leslie'};console.log(c[b]);
c[b] = 'hi';
console.log(c[b]);

// Protected; More on Node
let obj = { name: 'leslie'.age: 18 };
let sex = Symbol(a); obj[sex] ='male';
console.log('-- -- -- -- -- -- -- -- --');
for (const key in obj) {
  console.log(obj[key]); // No output sex
}
Copy the code

Set and WeakSet data structures (Demo12.js)

/** * Set */
/ / declare
let a = new Set(['Joe'.'bill']);
a.add('Ming');
console.log(a); // Set {' zhang ', 'Li ',' xiao Ming '}

/ / to heavy
let b = new Set(['a'.'b'.'c'.'a']);
console.log(b);

/ / search from
b.has('a'); // true
b.has('d'); // false

// delete - deletes the specified value; Clear - Deletes all
b.delete('c');
console.log('delete:', b);

// for of
for (const item of b) {
  console.log(item);
}

// forEach
b.forEach((val) = > console.log(val));

/ / the size attribute
console.log(b.size);

/** * WeakSet */
let weakObj = new WeakSet(a);let obj = { a: 'a'.b: 'b' };
let obj2 = { a: 'a'.b: 'b' };
weakObj.add(obj);
weakObj.add(obj2);
console.log('weakObj', weakObj);
Copy the code

Map Data structure (demo13.js)

Efficient and flexible

// json
let json = {
  name: 'leslie'.age: 18};console.log(json.name); // Need to traverse the object to find

// map =>
let map = new Map(a); map.set(json,'ima');
map.set('ima2', json);
map.set('ima3', json);
console.log(map);

// add, delete, and query map
// get
console.log(map.get(json)); // ima
// delete - deletes the specified value; Clear - Deletes all
map.delete('ima2');
console.log('after the delete:, map);
/ / the size attribute
console.log(map.size);
/ / to find
map.has('ima3'); // true
Copy the code

The Proxy agent (demo14. Js)

Proxy can be understood as a layer of “interception” before the target object. All external access to the object must pass this layer of interception. Therefore, Proxy provides a mechanism for filtering and rewriting external access

// Proxy ES6 enhanced object and function lifecycle hook functions (preprocessing)
let pro = new Proxy({add: function (val) {
      return val + 100;
    },
    name: 'I am Leslie'}, {// The first two parameters are mandatory and the third parameter is optional
    get: function (target, key, property) {
      console.log('come in get');
      return target[key];
    },
    // 4 parameters value: changed value Receiver: original value
    set: function (target, key, value, receiver) {
      console.log(`setting ${key} = ${value}`);
      return(target[key] = value); }},);console.log(pro.name);
pro.name = 'hello';
console.log(pro.name);

// apply
let target = function () {
  return 'I am Leslie';
};
let handler = {
  apply(target, ctx, args) {
    console.log('do apply');
    return Reflect.apply(... arguments); }};let pro2 = new Proxy(target, handler);
console.log(pro2());
Copy the code

Promise object (demo15. Js)

Promise is a solution to asynchronous programming that makes more sense and is more powerful than traditional solutions — callback functions and events. Fixed the ES5 callback hell issue.

/** * Promise to solve the ES5 callback hell problem * 1. Wash dishes and cook * 2. Sit down to eat * 3. Wash dishes */

let state = 1;
function step1(resolve, reject) {
  console.log('1. Start washing vegetables and cooking ');
  if (state === 1) {
    resolve('Wash and cook - done');
  } else {
    reject('Washing dishes and cooking - wrong'); }}function step2(resolve, reject) {
  console.log('2. Sit down to eat ');
  if (state === 1) {
    resolve('Sit down and eat. - Done.');
  } else {
    reject('Sit down and eat. - Mistake.'); }}function step3(resolve, reject) {
  console.log('3. Wash the dishes);
  if (state === 1) {
    resolve('Wash the dishes - done');
  } else {
    reject('Do the dishes - Wrong'); }}new Promise(step1)
  .then(function (val) {
    console.log('val:', val);
    return new Promise(step2);
  })
  .then(function (val) {
    console.log('val:', val);
    return new Promise(step3);
  })
  .then(function (val) {
    console.log('val:', val);
    console.log('the end');
  });
Copy the code

Class Class (demo16. Js)

/ / the class declaration
class Coder {
  // Class parameters
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
  name(val) {
    console.log(val);
    return val;
  }
  skill(val) {
    console.log(`The ${this.name('bill')}The skill is${val}`);
  }
  add() {
    return this.a + this.b; }}/ / use
let a = new Coder();
a.name('Joe');
a.skill('Play games');

let b = new Coder(1.2);
console.log(b.add());

// Class extends
class Htmler extends Coder {}

let c = new Htmler(2.3);
console.log(c.add());
Copy the code

Module (demo17.js module/)

/ / export export
/ / the import import
import { name, add } from './module/a';
console.log(name);
console.log(add(1.2));
Copy the code