preface

Recently, I began to re-learn the front end. I will share my notes with you during the learning process. I hope it will be helpful to you and we can grow together.

This article briefly lists some of the new features in ES6+, some of which are too broad to cover, so this article will cover them in detail in another article, such as Promise, Generator, etc.

The body of the

Let, const block-level scope, and var

  • Variables declared by lets and const are block-scoped in for and if statements. Variables in the block-scope cannot be used outside the scope
  • Let/const declarations no longer get declaration promotion. Using a variable before it is declared will result in a runtime error
Const param = 'param in if block'; if(true) {const param = 'param in if block'; console.log(param); //param in if block } console.log(param); // ReferenceError: Param is not definedCopy the code

  • A “temporary dead zone” occurs when a block-level scope declares a variable. An error occurs when a variable is used before a block-level scope declares a variable
// Temporary dead zone const I = 100; if(i) { console.log(i); //ReferenceError: Cannot access 'i' before initialization const i = 1000; }Copy the code

  • Const declares a constant, and the declaration must be initialized
// const const const I must be initialized; i = 10; console.log(i) //SyntaxError: Missing initializer in const declarationCopy the code

  • If a const declares a primitive type constant, it cannot be modified after initialization. References a constant of a type whose member variables can be modified;
// Const STR = 'STR '; str = 'str1'; //TypeError: Assignment to constant variable. const arr = [1, 2, 3]; arr[0] = 100; console.log(arr[0]) //100Copy the code

  • And var
A declarative way Variable ascension scope The initial value Repeat definition
var is Function level Don’t need allow
let no block-level Don’t need Don’t allow
const no block-level necessary Don’t allow

2. Deconstruction – Quickly extract elements from arrays/objects

  • An array of deconstruction

  • Separate deconstruction – Decompose an array into separate elements based on the array index

const arr = [1, 2, 3];

const [a, b, c] = arr;
console.log(a, b, c);//1,2,3
const [, , d] = arr;
console.log(d)//3
Copy the code

  • Default value, you can set the default value to the variable when you deconstruct it, if the array doesn’t have this element
const arr = [1, 2, 3]; const [, , , defaultVal = '4'] = arr; Console. log(' set defaults ',defaultVal);Copy the code

  • Residual deconstruction – use “… + variable name “to deconstruct remaining parameters into new array, can only be used once
const arr = [1, 2, 3];

const [e, ...rest] = arr;
console.log(rest)//[2, 3]
Copy the code

  • Application instance
// Split string const STR = 'xiaobai/18/200'; const strArr = str.split('/'); const [, age, ] = strArr; console.log(age)//18Copy the code

  • Object to deconstruct

  • Single/multiple deconstruction – similar to array deconstruction

 const obj = {name: 'xiaohui', age: 18, height: undefined};
 const {name, age} = obj;
 console.log(name, age) // 'xiaohui', 18
Copy the code

  • Deconstruct + Rename – Renames deconstructed variables
const obj = {name: 'xiaohui', age: 18, height: undefined};
const {mame: objMame} = obj;
console.log(objMame)
Copy the code

  • Default values – Sets default values for destruct variables
const obj = {name: 'xiaohui', age: 18, height: undefined};
const {mame: objMame} = obj;
console.log(objMame)
Copy the code

3. Template string

  • Usage:

  • Wrap the string with ‘ ‘

  • Function:

  • You can wrap, interpolate, and manipulate strings using label functions

  • Example:

  • Line feed/interpolation

// const STR = 'fdsjak fdsa' console.log(STR) // Interpolate const STRS = 'random: ${math.random ()}'; console.log(strs)Copy the code

  • Tag function – can handle and filter the string and interpolation of template strings
/** * string template function * @param {array} STRS an array of interpolated strings * @param {string} name Interpolated value, */ const tagFunc = (STRS, name, gender) => {const [str1, str2, str3] = STRS; const genderParsed = gender == "1" ? "Male" : "female "; Return str1 + name + str2 + str3 + genderParsed; // Return str1 + name + str2 + str3 + genderParsed; }; // Tagged template string, const person = {name: "xiaohui", gender: 1,}; Const result = tagFunc 'my name is ${person.name}. Gender is ${person.gender}'; console.log(result); // My name is xiaohui. Gender is maleCopy the code

4. String extension method

  • Includes – Whether it is included
  • StartsWith – does it start with something
  • EndsWith – does it end with something
const str = 'abcd'; console.log(str.includes('e')); //false console.log(str.startsWith('a')); //true console.log(str.endsWith('a'))//falseCopy the code

5. Default values & Remaining parameters

  • Sets default values for function parameters
Const defaultParams = function (name,age = 0) {return [age, name]}; console.log(defaultParams(1))Copy the code

  • The use of… The REST form sets the remaining parameters, supporting unlimited parameters
Const restParams = function(... args) { console.log(args.toString()); //1, 2, 3, 4, 5 } restParams(1, 2, 3, 4, 5)Copy the code

6. Expand the array

The use of… Expand the array

const arr = [1, 2, 3]; console.log(... arr); // Es5 equivalent to console.log.apply(console, arr)Copy the code

7. Arrow function

Features & Advantages:

  • 1. Simplify the writing of functions
  • 2. There is no this mechanism. This inherits from the context of the previous function, and if there is no previous function, it points to the window
  • 3. When used as an asynchronous callback function, the this pointing problem can be solved
const inc = n => n + 1; console.log(inc(100)) const obj = { name: 'aa', func() { setTimeout(() => { console.log(this.name); //aa }, 0); setTimeout(function() { console.log(this.name); //undefined }, 0); } } obj.func();Copy the code

8. Object literals are enhanced

  • For attributes of the same name, you can omit the key:value form.
  • Functions may omit the key: value form
  • You can just go to func(),
  • You can use computed attributes, such as {[math.random ()]: value}
/ * * * 1, enhances the object literal: * 1, of the same name attribute can be omitted key: value form, the key directly, * 2, function can be omitted key: * 3 value form, can be directly func (), * 4, you can use the computing properties, such as: {[Math.random()]: value} */ const arr = [1, 2, 3]; const obj = { arr, func(){console.log(this.arr)}, [Math.random()]: arr } console.log(obj)Copy the code

9.Object.assign(target1, target2, targetN)- Copy/merge objects

/** * Object.assign(target1, target2, ... Const obj1 = {a: 1, b: 2}; const obj1 = {a: 1, b: 2}; const obj2 = { a: 1, b: 2, }; const obj3 = Object.assign({}, obj1); obj3.a = 5; console.log(obj3, obj2, obj1);Copy the code

10.Object.is(value1, value2)

Function:

Compares whether two values are equal

Features:

  • There is no implicit conversion
  • You can compare +0,-0, NaN
console.log(NaN === NaN) //false
console.log(Object.is(NaN, NaN)) //true
console.log(0 === -0) // true
console.log(Object.is(0, -0))//false
console.log(Object.is(1, 1))//true
Copy the code

11.Proxy(object, handler)

Function:

  • Proxy for all of an object, including read and write operations and various operations listening

Usage:

const P = { n: "p", a: 19, }; const proxy = new Proxy(P, { get(target, property) { console.log(target, property); return property in target ? target[property] : null; }, defineProperty(target, property, attrs) { console.log(target, property, attrs); // throw new Error(' not allowed to change ')}, deleteProperty(target, property) {console.log(target, property); delete target[property]; }, set(target, property, value) { target[property] = value; }}); proxy.c = 100; console.log('pp',P);Copy the code

With the Object. DefinePropert contrast

Advantage:
  • Has a lot of attribute methods that defineProperty doesn’t have, such as:

  • Handler.getprototypeof () — object.getProtoTypeof listener for the method
  • Handler.setprototypeof () — object.setPrototypeof listener for the method.
  • Handler.isextensible () –Object. IsExtensible listener for the method.
  • Handler. PreventExtensions () – the Object. The listeners preventExtensions method.
  • Handler. GetOwnPropertyDescriptor () – the Object. The listeners getOwnPropertyDescriptor method.
  • Handler.defineproperty () — Listener for the object.defineProperty method.
  • Handler.has () — Listener for the in operator.
  • Handler.get () — The listener for the property read operation.
  • Handler.set () — The listener for the property setting operation.
  • Handler.deleteproperty () — Listener for the delete operator
  • Handler. OwnKeys () – Object. GetOwnPropertyNames method and Object getOwnPropertySymbols method of listeners.
  • Handler.apply () – Listeners for function call operations.
  • Handler.construct () – the listener of the new operator.
  • Arrays are easier to monitor

  • Non-intrusive access to the read and write of supervised objects

12.Reflect

Function:

Integrate all methods of Object operation, unified and convenient, the specific methods are as follows:

For unified operation of objects, integrating all methods related to Object

1, apply: similar to function.prototype

2, Reflect. The construct ()

New to the constructor is equivalent to executing a new target(… The args).

3, Reflect. DefineProperty ()

Similar to Object.defineProperty().

4, Reflect. DeleteProperty ()

The delete operator of the function is equivalent to the delete target[name].

5, Reflect the get ()

Gets the value of an attribute on the object, similar to target[name].

6, Reflect. GetOwnPropertyDescriptor ()

Similar to the Object. GetOwnPropertyDescriptor ().

7, Reflect. GetPrototypeOf ()

Similar to Object.getProtoTypeof (), gets the prototype of the target Object.

8, Reflect from the ()

Determining whether an object has a property is exactly the same as the in operator.

9, Reflect. IsExtensible ()

Similar to object.isextensible (). To determine whether an Object isExtensible, additional properties can be added

Object.seal and object. freeze are not extensible

10 and Reflect. OwnKeys ()

Returns an array containing all of its own properties (excluding inherited properties). Keys () similar to Object.keys() but not affected by Enumerable.

11, Reflect. PreventExtensions ()

Similar to object.preventExtensions (). Return a Boolean.

12, Reflect the set ()

A function that assigns values to attributes. Return a Boolean, true if the update was successful, false otherwise.

13, Reflect. SetPrototypeOf ()

Similar to Object.setPrototypeof ().

Example:

const obj = { name: 'reflect' } Reflect.preventExtensions(obj); // Disallow console.log(reflect. set(obj, 'age', 'xiaobai'))//false console.log(obj)//{name: 'reflect' } console.log(Reflect.isExtensible(obj, 'name'))//false console.log(Reflect.ownKeys(obj))//[ 'name' ]Copy the code

13.Promise

Purpose: To solve the problem of too deep nested callback in asynchronous programming

14. Class & Static methods & Inheritance

  • define

  • Use the class keyword to define classes

class Person{ constructor(props) { this.props = props; }}Copy the code

  • methods

  • Instance method, which needs to be instantiated before it can be called. This refers to the instance

  • Static methods, modified with the static modifier, can be called directly from the class name without instantiation. This does not refer to the instance, but to the current class

class Person{ constructor(props) { this.props = props; Eat () {} static run() {}} // call the static method person.run (); const person = new Person('props'); // Call the instance method person.eat();Copy the code

  • Inheritance: Subclasses inherit using the extends keyword and can inherit all properties of their parent class
class Student extends Person {
  constructor(props) {
    super(props);
  }
  printProps() {
    console.log(this.props);
  }
}

const student  = new Student('student');
student.printProps();
Copy the code

15.Set

Description:

A Set is a data structure similar to an array

Features:

  • Element uniqueness. Duplicate elements are not allowed
  • Adding duplicate elements with add is ignored

USES:

  • Array to heavy
  • Data is stored
Const arr = [1,3,1,1] const set = new set (arr); set.add(1).add(1); console.log(set.size)//2 const newArr = Array.from(set); console.log(newArr)//[ 1, 3 ]Copy the code

16.Map

Description:

Similar to Object, it stores data in the form of keys and values

The difference between:

The Map key is not implicitly converted to a string, but retains its original type

Example:

const map = new Map();
map.set(1, 1);
map.set('name', 'map')
map.set(obj, obj)
console.log(map.get(1)) //1
/**
    1 1
    name map
    { '1': 1, true: true, a: 'a' } { '1': 1, true: true, a: 'a' }
 */
map.forEach((val, key) => {console.log(key, val)})
Copy the code

17.Symbol

Description:

JavaScript sixth primitive data type, used to define a unique variable

  • Function:

  • Create a unique variable to solve the problem of duplicate object keys

  • Create private attributes for objects, classes, functions, and so on
  • Modify the toString tag of an object

  • Adds iterator attributes to the object

  • How do I get the Symbol attribute of an object?

  • Object.getOwnPropertySymbols(object)

  • The instance
// Object attributes have the same name; Const objSymbol = {[Symbol()]: 1, [Symbol()]: 2} console.log(objSymbol) // 2, create private attributes for objects, classes, functions, etc. const obj2 = { [name]: 'symbol', testPrivate() { console.log(this[name]); } } obj2.testPrivate(); // Define toString tags; console.log(obj2.toString()); obj2[Symbol.toStringTag] = 'xx'; console.log(obj2.toString()); //[object xx]Copy the code

18.for… of…

USES:

All reference data types are traversed in a uniform manner

Features:

You can terminate traversal at any time with break, but forEach can’t

Example:

Const arr = [1, 2, 3, 4]; for(const item of arr) { if(item > 3) { break; } if(item > 2) {console.log(item)}} const set = new set (); set.add('foo').add('bar'); For (const item of set) {console.log('set for of',item)} const map = new map (); map.set('foo', 'one').set('bar', 'two'); For (const [key, val] of map) {console.log('for map',key, val)} const obj = {name: "xiaohui", age: "10", store: [1, 2, 3], // Implement an iterable interface [symbol.iterator]: function () { const params = [this.name, this.age, this.store] let index = 0; return { next() { const ret = { value: params[index], done: index >= params.length, }; index++; return ret; }}; }}; for (const item of obj) { console.log("obj for of", item); }Copy the code

19. Iterator pattern

/ * *
* Iterator mode * function: Provides a unified external interface to access internal data through symbol. interator
* External can be accessed through for… of… To iterate over the internal data */
Const tods = {life: ["eat", "sleep"], learn: ["js", "dart"], // Add task work: ["sale", "customer"], [Symbol. Iterator]: function () { const all = []; Object.keys(this).forEach(key => { all.push(... this[key]) }) let index = 0; return { next() { const ret = { value: all[index], done: index >= all.length, }; index++; return ret; }}; }}; for (const item of tods) { console.log(item); }Copy the code

20. The Generator Generator

  • Generator
  • Add * to the front of the function to generate a generator
  • Usually used with the yield keyword
  • The biggest feature, lazy execution, next will be executed down
  • It is used to solve the problem that the asynchronous callback is too deep
Function * createIdGenerator() {let id = 1; while (id<3) yield id++; } const createId = createIdGenerator(); console.log(createId.next()); //{ value: 1, done: false } console.log(createId.next()); //{ value: 2, done: false } console.log(createId.next()); //{ value: undefined, done: true } const todos = { life: ["eat", "sleep", "baba"], learn: ["es5", "es6", "design pattern"], work: ["b", "c", "framework"], [Symbol.iterator]: function* () { const all = [...this.life, ...this.learn, ...this.work]; for(const i of all) { yield i; }}}; for(const item of todos) { console.log(item) }Copy the code

21. – es2016 includes function

Determine if an array contains an element that contains NaN. Solve the problem that indexOf cannot find NaN

// includes const arr = ["foo", "bar", "baz", NaN]; // Includes const arr = ["foo", "bar", "baz", NaN]; console.log(arr.includes(NaN)); //true console.log(arr.indexOf(NaN)); / / 1Copy the code

22.** operator – ES2016

Index of operation

* * / / / / index operator es5 twenty in the power of the console, log (math.h pow (2, 10)); // es6 = 2 ^ 10 console.log(2 ** 10);Copy the code

23. – es2017 values function

Returns the value of an object as an array

const obj = { foo: 1, bar: 2, baz: 3, }; console.log(Object.values(obj)); //[1, 2, 3]Copy the code

24. – es2017 entries function

Returns an object as a key-value pair to a two-dimensional array, allowing it to use for… of… traverse

const obj = {
  foo: 1,
  bar: 2,
  baz: 3,
};
console.log(Object.entries(obj));
const entry = Object.entries(obj);
for (const [key, value] of entry) {
  console.log(key, value);
}
Copy the code

25.Object.getOwnPropertyDescriptors(obj)-es2017

Gets the description of an object

You can make a full copy of the Object with the description obtained along with Object.defineProperties, including get and set methods

/ / getOwnPropertyDescriptors / / ordinary the get method const objGet = {foo: 1, bar: 2, get getCount () {return enclosing foo + enclosing the bar; }}; Const objGet1 = object. assign({}, objGet); const objGet1 = object. assign({}, objGet); objGet1.bar = 3; console.log(objGet1.getCount); //3 // descriptors const descriptors = Object.getOwnPropertyDescriptors(objGet); console.log("des", descriptors); // Copy the Object to descriptors, including get, set const objGet2 = object.defineProperties ({}, descriptors); objGet2.bar = 3; console.log(objGet2.getCount); / / 4Copy the code

PadStart, padEnd function -es2017

Appends the specified string before or after the string

Parameters:

TargetLenght: Target length after filling

PadString: indicates the filled string

Rules:

1. If the filled string exceeds the target length, it will be truncated at the specified length

2. If the padding string is too short, it will be filled with Spaces

3. PadString does not pass a value and is padded with Spaces

Function:

Used to align string output

/** * foo................. |1 barbar.............. |2 bazbazbaz........... |3 */ console.log(`${key.padEnd(20, '.')}${value.toString().padStart(2, '|')}`)Copy the code