ES6 new features

ES6 new features

ECMAScript

Overview

ECMAScript, or ES, is the standard of JavaScript, and JavaScript is the implementation of ECMAscript.

ECMAScript2015 is the representative version of es. Compared with the previous version, it has updated a lot of content. ES6 is the collective name of the new standard after ES2015. The changes of ES6 compared to ES5.1 can be divided into four categories:

  • Solve some problems and deficiencies in the original syntax, such as let and const keywords;

  • Enhancements to the original syntax, such as deconstruction, expansion, and parameter default values, etc.;

  • Brand new objects, methods and functions, such as Promise, Proxy, etc.;

  • Brand new data types and data structures, such as Symbol, Map, etc.

let and block scope

Scope: The accessible scope of variables and functions, that is, the scope controls the visibility and life cycle of variables and functions.

Before ES6, there were only two scopes: global scope and function scope.

With the update of the version, let and const keywords appeared, and using them to define variables will form a block-level scope

//global scope and function scope var n = 1 ; //defined in the global scope function fn () { var n = 1 ; //Defined in a function, the variable can only be accessed in this function } //------------------------------------------------ --------------------- //block-level scope if (flag) { let n = 1 //defined in the if code block } console .log(n) //Print the variable defined inside the if outside the if and report the variable is not defined Copy code

When defining a variable, the var keyword will promote the variable, and let will produce a temporary dead zone:

//var console .log(a) var a = 1 //This will not report an error, only an undefined will be printed //------------------------------------------------ --------------------- Console .log (b) the let b = 1 //this time will be reported in a reference error, b is not defined copy the code

When adding events to the dom element through a loop before es6, some "unexpected" problems would also arise due to the scope problem:

var lis = document .getElementsByClassName( 'li' ) for ( var i = 0 ; i <lis.length; i ++) { lis[i].onClick = function () { console .log(i) } } Copy code

In success to

li
After adding the click event, no matter which click
li
The printed value is always
lis.length-1
, The effect is not the same as we expected. This is also because after defining the counter i with var, i is defined in the global. When the loop ends, the value of i has become
lis.length-1
, Then click
li
Of course, the printed result is the same value. Before es6, if you need to solve this problem, you need to use closures:

var lis = document .getElementsByClassName( 'li' ) for ( var i = 0 ; i <lis.length; i ++) { lis[i].onClick = ( function ( count ) { return function () { console .log(count) } })(i) //This should be correct } Copy code

After the let keyword appears, just use let to define the counter to solve the problem caused by scope:

let lis = document .getElementsByClassName( 'li' ) for ( let i = 0 ; i <lis.length; i ++) { lis[i].onClick = function () { console .log(i) } } Copy code

const

The const keyword is basically the same as let, except that const defines a constant and cannot be modified after the definition:

const A = . 4 A = . 5 duplicated code

A type error will be reported at this time

Assignment to constant variable
.

Of course, the modification here refers to modifying the memory address of the member. For reference data types, it is no problem to modify only its internal data:

const obj = {} = obj.name 'I want to learn' copy the code

This situation is not a problem, but if the

obj
Pointing to another memory address, it will still report an error

const obj = {} obj = [] //Console: Uncaught TypeError: Assignment to constant variable. Copy the code

Deconstruction

Array destructuring

Before es6, when we want to extract the elements in the array, we will use the index to get the value

const arr = [ 0 , 1 , 2 ] const n1 = arr[ 0 ] const n2 = arr[ 1 ] const n3 = arr[ 2 ] //print n1, n2, n3 is: 012 copy the code

After the es6 update, we can take values through the destructuring of the array

const arr = [ 0 , 1 , 2 ] const [n1, n2, n3] = arr //print n1, n2, n3 is: 012 copy the code

Of course, there are the following situations:

  1. There is a value you don t want to take, replace it with a space
const arr = [ 0 , 1 , 2 ] const [,, n1] = arr //Print n1 as: 2Copy code
  1. The length of the array is greater than the length of the value
const arr = [ 0 , 1 , 2 ] const [,n1] = arr //print n1 as: 1 copy the code
  1. The length of the array is less than the length of the value
const arr = [ 0 ] const [n1, n2] = arr //print n1, n2 is: 0 undefined copy the code

Object deconstruction

Unlike array deconstruction using variables to align corresponding elements, object deconstruction is matched by attribute names. If the corresponding attribute name is not matched, it will become undefined. At the same time, you can also alias variables when deconstructing

const obj = { name : 'study hard' , method : 'study' } const {name, age, method : m} = obj //name is printed as:'study well', age is printed as: undefined, m is printed as:'learning' duplicated code

Template string

Before es6, strings were represented by double quotation marks and single quotation marks, such as

'string'
or
"string"
. If you want to wrap the string, you have to use/n to indicate it. Deeper, if you want to add a variable in the middle of the string, you have to concatenate the string:

const name = 'study hard ' const str = 'I want' + name + 'now' //print str is: 'I want to learn the' Copy the code

If you encounter multiple strings and multiple variables splicing, it will be more messy, and the template string of es6 greatly reduces such operations.

The template string is wrapped with backquotes. Under normal circumstances, it can be used as an ordinary one. However, in the case of string splicing, you can use interpolation expressions to embed variables or even simple standard js statements:

const name = 'study hard ' const str = `I want ${name} ` //print the results as follows: 'I want to learn the' Copy the code

Template string tag

In the template string, you can also add a tag function to it:

function tagFn ( string ) { return string } const name = ' cinit ' const toDo = 'study hard ' const RES = tagFn `I $ {name} to $ {toDo} a` //print result RES: [ 'I', 'to', 'a'] to copy the code

It can be seen that the label function divides the template string by the position of the variable. At the same time, it can also be

tagFn
Add the corresponding variable to the formal parameter to get the corresponding value:

function tagFn ( string, name, toDo ) { return string[ 0 ] + name + string[ 1 ] + toDo + string[ 2 ] } const name = ' cinit ' const toDo = 'study hard ' const RES = tagFn `I $ {name} to $ {toDo} a` //RES print result is: 'I want to learn the cinit' Copy the code

Thus, the variables in the template string can be processed in the label function:

function tagFn ( string, name, toDo ) { name = name === 'cinit' ? 'I' : 'Others' return string[ 0 ] + name + string[ 1 ] + toDo + string[ 2 ] } const name = ' cinit ' const toDo = 'study hard ' const RES = tagFn `I $ {name} to $ {toDo} a` //RES print the results as follows: 'I learned I was going to' copy the code

String extension method

  • includes

    includes
    Method can determine whether the string contains the target character

    const STR = 'learn' Console .log (str.includes ( 'good' )) //print result: true copy the code
  • startsWith

    startsWith
    Can judge whether the string starts with the target character

    const STR = 'learn' Console .log (str.startsWith ( 'good' )) //print result: true copy the code
  • endsWith

    endsWith
    Can judge whether the string ends with the target character

    const STR = 'learn' Console .log (str.endsWith ( 'learning' )) //print result: true copy the code

Function default value

For some functions, you can set default values to simplify function calls. Before es6, most of them were implemented in this way:

function fn ( name ) { name = name === undefined ? 'cinit' : name console .log(name) } fn() fn( 'wo' ) //function calls the print result: //'cinit' //'WO' Copy the code

After es6, the code can be simplified to:

function fn ( name = 'cinit' ) { console .log(name) } fn() fn( 'wo' ) //function calls the print result: //'cinit' //'WO' Copy the code

Remaining operator

Before es6, the parameters passed in in a function can be obtained by arguments inside the function:

function fn () { console .log( arguments ) } Fn ( 1 , 2 , 2 ) //print result is: [1, 2, 2] copy the code

This arguments is a pseudo-array

After es6, we can pass the remaining operators

...
To get the remaining parameters:

function fn ( ...args ) { console .log(args) } Fn ( 1 , 2 , 2 ) //print result is: [1, 2, 2] copy the code

after

...
Operation,
args
Form an array to receive the parameters passed in fn.

Array expansion

...
Not only can be used as a remaining operator, but also can be used to expand an array

Before es6, if you want to print every element in the array at the same time, you usually pass

apply
Method passes in an array for printing:

const arr = [ 1 , 2 , 3 ] console .log.apply( console , arr) //The print result is: 1 2 3Copy code

After es6, it can be simplified to:

const arr = [ 1 , 2 , 3 ] console .log(...arr) //The print result is: 1 2 3Copy code

...
Pass each item of the array into the function in turn

Arrow function

The arrow function of es6 simplifies the definition of the function to a certain extent, and it contains the following characteristics:

  • use

    =
    ,
    >
    with
    {}
    To describe a function

    const fn = ( num1, num2 ) => { num1 += 1 num2 += 2 return num1 + num2 } Copy code
  • The function must be declared in the way of defining variables

    //wrong function ( num1, num2 ) => { num1 += 1 num2 += 2 return num1 + num2 } //right const fn = ( num1, num2 ) => { num1 += 1 num2 += 2 return num1 + num2 } Copy code
  • When there is only one formal parameter of the function, the parentheses can be omitted

    const fn = num => { num += 1 return num } Copy code
  • When the function body has only one (return) statement, the braces can be omitted

    const Fn = NUM => NUM + . 1 duplicated code
  • Within the arrow function

    this
    Point to the context in which it was defined
    this
    direction

Object literal enhancement

Before es6, when declaring variables using object literals, you may encounter the following situations

const name = 'study well' const fn = function () {} const obj = { //The key value name of the attribute is the same name : name, fn : fn, } //add dynamic attribute name to an object obj [ the Math .random ()] = . 1 copy the code

After es6, it can be changed to the following method:

const name = 'study well' const fn = function () {} const obj = { //The key value name of the attribute is the same, only write it once name, fn, //Use square brackets to wrap the variable directly when declaring the variable [ Math .random()]: 1 } Copy code

Object extension method

Object.assign

Object.assign()
Methods are used to assign the values of all enumerable properties from one or more source objects to target objects. It will return the target object.

syntax:

Object.assign (target, ... sources) Copy the code

parameter:

target
:target.

sources
: Source object.

return value:

target.

const target = { a : 1 , b : 2 }; const source = { b : 4 , c : 5 }; const returnedTarget = Object .assign(target, source); console .log(target); //The print result is: {a: 1, b: 4, c: 5} Console .log (returnedTarget); //print result is: {a: 1, b: 4, c: 5} copy the code

If the attributes in the target object have the same key, the attributes will be overwritten by the attributes in the source object. The attributes of the later source objects will similarly override the attributes of the previous source objects.

Object.assign
The method will only copy the enumerable properties of the source object itself to the target object. This method uses the source object's
[[Get]]
And the target audience
[[Set]]
, So it will call related getters and setters. Therefore, it assigns attributes instead of just copying or defining new attributes. If the merge source contains getters, this may make it unsuitable for merging new properties into the prototype. In order to copy the attribute definition (including its enumerability) to the prototype, use
Object.getOwnPropertyDescriptor()
with
Object.defineProperty()
.

Type and
Symbol
The attributes of the type are copied.

In the event of an error, for example, if the property is not writable, it will raise

, If any attributes are added before the error is raised, you can change
target
Object.

note,

Object.assign
Not in those
source
Object value
null
or
undefined
Throws an error when.

For deep copy, other methods need to be used, because

Object.assign()
The (enumerable) attribute value is copied.

If the source value is a reference to an object, it will only copy its reference value.

const log = console .log; function test () { 'use strict' ; let obj1 = { a : 0 , b : { c : 0 }}; let obj2 = Object .assign({}, obj1); log( JSON .stringify(obj2)); //{a: 0, b: {c: 0}} obj1.a = 1 ; log( JSON .stringify(obj1)); //{a: 1, b: {c: 0}} log( JSON .stringify(obj2)); //{a: 0, b: {c: 0}} obj2.a = 2 ; log( JSON .stringify(obj1)); //{a: 1, b: {c: 0}} log( JSON .stringify(obj2)); //{a: 2, b: {c: 0}} obj2.bc = 3 ; log( JSON .stringify(obj1)); //{a: 1, b: {c: 3}} log( JSON .stringify(obj2)); //{a: 2, b: {c: 3}} //Deep Clone obj1 = { a : 0 , b : { c : 0 }}; let obj3 = JSON .parse( JSON .stringify(obj1)); obj1.a = 4 ; obj1.bc = 4 ; log( JSON .stringify(obj3)); //{a: 0, b: {c: 0}} } test(); Copy code

Object.is

Object.is()
Method to determine whether two values are the same value.

syntax:

Object .is (VALUE1, value2); duplicated code

parameter:

value1
: The first value to be compared.

value2
: The second value to be compared.

return value:

A Boolean type indicates whether two parameters are the same value.

Object .is( 'foo' , 'foo' ); //true Object .is( window , window ); //true Object .is( 'foo' , 'bar' ); //false Object .is([], []); //false var foo = { a : 1 }; var bar = { a : 1 }; Object .is(foo, foo); //true Object .is(foo, bar); //false Object .is( null , null ); //true Specific examples// Object .is ( 0 , - 0 ); //to false Object .is ( 0 , + 0 ); //to true Object .is (- 0 , - 0 ); //to true Object .is ( NaN3 , 0/0 ); //to true copy the code

Object.is()
Method to determine whether two values are the same value. The two values are equal if the following conditions are met:

  • All
    undefined
  • All
    null
  • All
    true
    or
    false
  • Both are strings of the same length and the same characters are arranged in the same order
  • Are all the same object (meaning that each object has the same reference)
  • Are all numbers and
    • All
      +0
    • All
      -0
    • All
      NaN
    • Or both are non-zero and non-
      NaN
      And the same value

versus

==
The calculation is different.
==
The operator performs a coercive conversion on the variables on both sides (if they are not the same type) before judging equality (the result of this behavior will be
"" == false
Judged as
true
), while
Object.is
The values on both sides will not be forced.

versus

===
The calculations are also different.
===
Operator (also includes
==
Operator) will number
-0
with
+0
Treat as equal, and treat
Number.NaN
versus
NaN
Treated as not equal.

Proxy

The Proxy object is used to create a proxy for an object, so as to realize the interception and customization of basic operations (such as attribute lookup, assignment, enumeration, function call, etc.).

the term:

  • handler: A placeholder object containing a trap, which can be translated into a processor object.

  • traps: Provide methods for accessing attributes. This is similar to the concept of traps in operating systems.

  • target: The object virtualized by the Proxy. It is often used as a storage backend for the proxy. Validate invariants about the non-extensibility or non-configurable properties of the object according to the target (the semantics remain unchanged).

syntax:

const P = new new the Proxy (target, Handler) copy the code

parameter:

target: to use

Proxy
The target object of the package (can be any type of object, including native arrays, functions, or even another proxy).

handler: An object that usually takes a function as an attribute. The function in each attribute defines the agent when performing various operations.

p
the behavior of.

method:

Proxy.revocable()
: Create a revocable
Proxy
Object.

Methods of the handle object:

handler
The object is a placeholder object that holds a batch of specific properties. It contains
Proxy
The various traps (trap).

All catchers are optional. If a catcher is not defined, then the default behavior of the source object will be retained.

  • handler.getPrototypeOf()

    Object.getPrototypeOf
    Method catcher.

  • handler.setPrototypeOf()

    Object.setPrototypeOf
    Method catcher.

  • handler.isExtensible()

    Object.isExtensible
    Method catcher.

  • handler.preventExtensions()

    Object.preventExtensions
    Method catcher.

  • handler.getOwnPropertyDescriptor()

    Object.getOwnPropertyDescriptor
    Method catcher.

  • handler.defineProperty()

    Object.defineProperty
    Method catcher.

  • handler.has()

    in
    Operator catcher.

  • handler.get()

    The catcher for attribute read operations.

  • handler.set()

    The catcher for property setting operations.

  • handler.deleteProperty()

    delete
    Operator catcher.

  • handler.ownKeys()

    Object.getOwnPropertyNames
    Methods and
    Object.getOwnPropertySymbols
    Method catcher.

  • handler.apply()

    The catcher for function call operations.

  • handler.construct()

    new
    Operator catcher.

Example:

//Basic example const p = new Proxy ({}, { get : function ( obj, prop ) { return prop in obj? Obj[prop]: 37 ; }); pa = 1 ; pb = undefined ; Console .log (PA, Pb); //. 1, undefined Console .log ( 'C' in P, PC); //to false, 37 [ duplicated code
//Verify the value passed to an object let validator = { set : function ( obj, prop, value ) { if (prop === 'age' ) { if (! Number .isInteger(value)) { throw new TypeError ( 'The age is not an integer' ); } if (value> 200 ) { throw new RangeError ( 'The age seems invalid' ); } } //The default behavior to store the value obj[prop] = value; //indicates success return true ; } }; let person = new Proxy ({}, validator); person.age = 100 ; console .log(person.age); //100 person.age = 'young' ; //Throws an exception: Uncaught TypeError: The age is not an integer = person.age 300 ; //throws an exception: Uncaught RangeError: The age seems invalid copy the code

Reflect

Reflect is a built-in object that provides methods to intercept JavaScript operations. These methods are the same as those of proxy handlers.

Reflect
It is not a function object, so it is not constructible.

Reflect provides a complete set of operations on objects

Unlike most global objects

Reflect
Is not a constructor, so it cannot be called by the new operator, or the
Reflect
The object is called as a function.
Reflect
All properties and methods of are static (like
Math
Object).

Reflect
The object provides the following static methods, which have the same names as proxy handler methods.

Some of these methods are compatible with

Object
Same, although there are some subtle differences between the two.

Static method:

  • Reflect.apply(target, thisArgument, argumentsList
    :

    To call a function, you can also pass in an array as the call parameter. with

    Function.prototype.apply()
    The function is similar.

  • Reflect.construct(target, argumentsList[, newTarget])
    :

    On the constructor

    new
    Operation, equivalent to executing
    new target(...args)
    .

  • Reflect.defineProperty(target, propertyKey, attributes)
    :

    with

    Object.defineProperty()
    similar. If the setting is successful, it will return
    true

  • Reflect.deleteProperty(target, propertyKey)
    :

    As a function

    delete
    Operator, equivalent to execution
    delete target[name]
    .

  • Reflect.get(target, propertyKey[, receiver])
    :

    Get the value of an attribute on the object, similar to

    target[name].

  • Reflect.getOwnPropertyDescriptor(target, propertyKey)
    :

    Similar to

    Object.getOwnPropertyDescriptor()
    . If the attribute exists in the object, then return the corresponding attribute descriptor, otherwise return
    undefined
    .

  • Reflect.getPrototypeOf(target)
    :

    Similar to

    Object.getPrototypeOf()
    .

  • Reflect.has(target, propertyKey)
    :

    Determine whether an object has a certain attribute, and

    in
    The functions of the operators are exactly the same.

  • Reflect.isExtensible(target)
    :

    Similar to

    Object.isExtensible()
    .

  • Reflect.ownKeys(target)
    :

    Returns an array containing all its own properties (not including inherited properties). (Similar to

    Object.keys()
    , But will not be affected by
    enumerable influence
    ).

  • Reflect.preventExtensions(target)
    :

    Similar to

    Object.preventExtensions()
    . Return a
    Boolean
    .

  • Reflect.set(target, propertyKey, value[, receiver])
    :

    A function that assigns a value to an attribute. Return a

    Boolean
    , If the update is successful, return
    true
    .

  • Reflect.setPrototypeOf(target, prototype)
    :

    Function to set object prototype. Return a

    Boolean
    , If the update is successful, return
    true.

Example:

//Check whether an object has specific attributes const duck = { name : 'Maurice' , color : 'white' , greeting : function () { console .log( `Quaaaack! My name is ${ this .name} ` ); } } The Reflect .has (Duck, 'Color' ); //to true the Reflect .has (Duck, 'Haircut' ); //to false copy the code
//Add a new attribute to an object the Reflect .set (Duck, 'Eyes' , 'Black' ); //Returns "to true" IF successful //"Duck" The now the contains Property "Eyes: 'Black'" copy the code

Promise

See

Class

In object-oriented programming, a class (

class
) Defines the characteristics of an object. A class is a template for defining object properties and methods.

Before ES6, you can pass

Function
To implement the class

function Student ( name ) { this .name = name } Student.prototype.greet = function () { console .log( 'hi' ) } Copy code

ES6 introduction

class
After that, it can be changed to the following form:

class Student { constructor ( name ) { this .name = name } greet () { console .log( 'hi' ) } } Copy code

Similar to Java, this method can also be passed

static
with
extends
Implement static methods and inheritance:

class Student { constructor ( name ) { this .name = name } greet () { console .log( 'hi' ) } } class LiHua extends Student { constructor ( name, major ) { super (name) this .major = major } static study () { console .log( 'study English' ) } sayHi () { super .greet() } } Copy code

Set

Set
An object is a collection of values, and you can iterate its elements in the order of insertion. The elements in the Set will only appear once , that is, the elements in the Set are unique.

Set
Objects allow you to store any type of unique value, whether it is a primitive value or an object reference.

NaN
with
undefined
Can be stored in Set,
NaN
Are considered the same value.

set
The data structure itself is a constructor.

Instance attributes:

  • size
    : Returns the number of values in the Set object

Example method:

  • Set.prototype.add(value)
    :

    in

    Set
    Add an element to the end of the object. Return to that
    Set
    Object.

  • Set.prototype.clear()
    :

    Remove

    Set
    All elements within the object.

  • Set.prototype.delete(value)
    :

    Remove

    Set
    The element equal to this value in, return
    Set.prototype.has(value)
    The value that will be returned before this operation (that is, if the element exists, return
    true
    , Otherwise return
    false
    )

  • Set.prototype.has(value)
    :

    Will return later

    false
    .

  • Set.prototype.entries()
    :

    Return a new iterator object that contains

    Set
    The value of all the elements in the object in the order of insertion
    [value, value]
    Array. In order to make this method and
    Map
    The objects remain similar, and the key and value of each value are equal.

  • Set.prototype.forEach(callbackFn[, thisArg])
    :

    In the order of insertion, callBackFn is called once for each value in the Set object. If provided

    thisArg
    Parameters, in the callback
    this
    Will be this parameter.

  • Set.prototype.has(value)
    :

    Returns a boolean value, indicating that the value is in

    Set
    Exist or not.

  • Set.prototype.keys()
    :

    versus**

    values()
    ** The method is the same, returns a new iterator object, the object contains
    Set
    The value of all elements in the object in the order of insertion.

  • Set.prototype.values()
    :

    Return a new iterator object that contains

    Set
    The value of all elements in the object in the order of insertion.

//Example let mySet = new Set (); mySet.add( 1 ); //Set [1] mySet.add( 5 ); //Set [1, 5] mySet.add( 5 ); //Set [1, 5] mySet.add( "some text " ); //Set [1, 5, "some text"] let o = { a : 1 , b : 2 }; mySet.add(o); mySet.add({ a : 1 , b : 2 }); //o points to a different object, so no problem mySet.has( 1 ); //true mySet.has( 3 ); //false mySet.has( 5 ); //true mySet.has( Math .sqrt( 25 )); //true mySet.has( " Some Text" .toLowerCase()); //true mySet.has(o); //true mySet.size; //5 mySet.delete( 5 ); //true, 5 is removed from the set mySet.has( 5 ); //false, 5 has been removed mySet.size; //4, just removed a value console .log(mySet); //logs Set(4) [1, "some text", { }, { }] in Firefox //logs Set(4) {1, "some text", { } , {...}} in Chrome copy the code
//Used for array deduplication const numbers = [ 2 , 3 , 4 , 4 , 2 , 3 , 3 , 4 , 4 , 5 , 5 , 6 , 6 , 7 , 5 , 32 , 3 , 4 , 5 ] console .log ([... new new the Set (Numbers)]) //[2,. 3,. 4,. 5,. 6,. 7, 32] copy the code

Map

Map
The object stores key-value pairs and can remember the original insertion order of the keys. Any value (object or primitive value) can be used as a key or a value.

**

Objects
with
Maps
**

Similarly, they all allow you to access a value by key, delete a key, and check whether a key is bound to a value. Therefore (and there is no other built-in alternative) in the past we have always treated objects as

Maps
use. but
Maps
with
Objects
There are some important differences, used in the following situations
Map
Would be a better choice:

MapObject
Unexpected key
Map
By default, no keys are included. Contains only explicitly inserted keys.
One
Object
There is a prototype, the key name on the prototype chain may conflict with the key name you set on the object. Although ES5 is available
Object.create(null)
To create an object without a prototype, but this usage is not very common.
Type of keyOne
Map
The key of can be any value , including functions, objects, or any basic type.
One
Object
The key must be a
String
Or
Symbol
.
Key sequence
Map
The keys in are ordered. Therefore, when iterating, a
Map
The object returns the key value in the order of insertion.
One
Object
The keys are unordered. Note: Since the ECMAScript 2015 specification, objects do retain the creation order of string and Symbol keys; therefore, iterating on an object with only string keys will generate keys in the order of insertion.
Size
Map
The number of key-value pairs can be easily passed
size
Property acquisition
Object
The number of key-value pairs can only be calculated manually
Iteration
Map
It is iterable, so it can be iterated directly.
Iterate one
Object
It needs to get its key somehow before iterating.
performanceIt performs better in scenarios where key-value pairs are frequently added and deleted.No optimization is made in scenarios where key-value pairs are frequently added and deleted.

Create a Map object

const m = new new the Map () to copy the code

Map constructor properties:

  • Map.length
    : The value of the attribute length is 0. Want to calculate one
    Map
    The number of entries in, use
    Map.prototype.size
    .

Map instance properties:

  • Map.prototype.constructor
    : Returns a function, which creates the prototype of the instance. The default is
    Map
    function.

  • Map.prototype.size
    : Returns the number of key/value pairs of the Map object.

Map instance method:

  • Map.prototype.clear()
    :

    Remove all key/value pairs of the Map object.

  • Map.prototype.delete(key)
    :

    in case

    Map
    The element exists in the object, remove it and return
    true
    ; Otherwise return if the element does not exist
    *false*
    . Then call
    Map.prototype.has(key)
    Will return
    false
    .

  • Map.prototype.entries()
    :

    Return a new

    Iterator
    Object, which contains the information of each element in the Map object in the order of insertion
    [key, value]
    Array.

  • Map.prototype.forEach(callbackFn[, thisArg])
    :

    In the order of insertion,

    Map
    The callbackFn function is called once for each key-value pair in the object. If thisArg is provided for forEach, it will be used as this value in each callback.

  • Map.prototype.get(key)
    :

    Returns the value corresponding to the key, or undefined if it does not exist.

  • Map.prototype.has(key)
    :

    Returns a Boolean value indicating whether the Map instance contains the value corresponding to the key.

  • Map.prototype.keys()
    :

    Return a new

    Iterator
    Object, which contains the key of each element in the Map object in the order of insertion .

  • Map.prototype.set(key, value)
    :

    Set the value of the key in the Map object. Return the Map object.

  • Map.prototype.values()
    :

    Return a new

    Iterator
    Object, which contains the value of each element in the Map object in the order of insertion .

//Example let myMap = new Map (); let keyObj = {}; let keyFunc = function () {}; let keyString = 'a string' ; //Add key myMap.set(keyString, "value associated with key'a string'" ); myMap.set(keyObj, "value associated with key keyObj" ); myMap.set(keyFunc, "value associated with key keyFunc" ); myMap.size; //3 //Read the value myMap.get(keyString); //"The value associated with the key'a string'" myMap.get(keyObj); //"The value associated with the key keyObj" myMap.get(keyFunc); //"Value associated with key keyFunc" myMap.get( 'a string' ); //"The value associated with the key'a string' " //because keyString ==='a string' myMap.get({}); //undefined, because keyObj != = {} myMap.get( function () {}); !//undefined, because keyFunc == function () {} copy the code
//Iteration //for...of... let myMap = new Map (); myMap.set( 0 , "zero" ); myMap.set( 1 , "one" ); for ( let [key, value] of myMap) { console .log(key + "=" + value); } //Two logs will be displayed. One is "0 = zero" and the other is "1 = one" for ( let key of myMap.keys()) { console .log(key); } //Two logs will be displayed. One is "0" and the other is "1" //forEach myMap.forEach( function ( value, key ) { console .log(key + "=" + value); }) //Two logs will be displayed. A is "0 = zero" and the other is "1 = one" copy the code

Symbol

Symbol is a basic data type.

Symbol()
The function returns the value of the symbol type, which has static properties and static methods. Its static properties will expose several built-in member objects; its static methods will expose the global symbol registration, which is similar to the built-in object class.

Each slave

Symbol()
The returned symbol values are all unique. A symbol value can be used as an identifier for an object property; this is the only purpose of the data type.

//Example const symbol1 = Symbol (); const symbol2 = Symbol ( 42 ); const symbol3 = Symbol ( 'foo' ); console .log( typeof symbol1); //expected output: "symbol" console .log(symbol2 === 42 ); //expected output: false console .log(symbol3.toString()); //expected output: "Symbol(foo)" console .log( Symbol ( 'foo' ) === Symbol ( 'foo' )); //expected output: false typeof the Symbol () === 'Symbol' typeof the Symbol ( 'foo' ) === 'Symbol' typeof the Symbol .iterator === 'Symbol' duplicated code

Symbol.iterator
:

A method that returns the default iterator of an object.

Symbol.hasInstance
:

A method to determine whether the object recognized by a constructor object is an instance of it.

Symbol.isConcatSpreadable
:

A Boolean value indicating whether an object should be flattened into its array elements.

Symbol.unscopables
:

The value of an object that owns and inherits the attribute name is excluded from related objects bound to the environment.

Symbol.species
:

A constructor function for creating derived objects.

Symbol.toPrimitive
:

A method to convert objects into basic data types.

Symbol.toStringTag
:

The string value used for the default description of the object.

method:

Symbol.for(key)
:

Use the given key to search for an existing symbol, and return the symbol if found. Otherwise, a new symbol will be created in the global symbol registry with the given key.

Symbol.prototype.toString()

Returns the string containing the Symbol descriptor. cover

Object.prototype.toString()
method.

Symbol.prototype.valueOf()

return

Symbol
The initial value of the object.. cover
Object.prototype.valueOf()
method.

Tips:

  • Symbols in

    for...in
    Not enumerable in iteration. In addition,
    Object.getOwnPropertyNames()
    Will not return the attributes of the symbol object, but can be used
    Object.getOwnPropertySymbols()
    Get them.

  • When using JSON.stringify(), attributes with symbol values as keys are completely ignored.

for...of

for...of
Statements in iterable objects (including
Array
,
Map
,
Set
,
String
,
TypedArray
,
arguments
,
HTMLCollection
Objects, etc.) create an iteration loop, call a custom iteration hook, and execute statements for each different attribute value.

//Sample iteration Array const array1 = [ 'a' , 'b' , 'c' ]; for ( const element of array1) { console .log(element); } Output expected//: "A" //Output expected: "B" //Output expected: "C" copy the code

Compared to the array

forEach
,
for...of
Can be used when iterating over the array
break
,
throw continue
or
return
termination. In these cases, the iterator is closed.

Iterator interface

Iterative protocol

As a set of supplementary specifications for ECMAScript 2015, the iteration protocol is not a new built-in implementation or syntax, but a protocol . These protocols can be implemented by any object that follows certain conventions.

The iterative protocol is specifically divided into two protocols: iterable protocol and iterator protocol .

Iterable protocol

The iterable protocol allows JavaScript objects to define or customize their iterative behavior, for example, in a

for..of
In the structure, which values can be traversed to. Some built-in types are also built-in iterable objects, and have default iteration behavior, such as
Array
or
Map
, While other built-in types are not (such as
Object
)).

To be an iterable object, an object must implement

Symbol.iterator
method. This means that the object (or an object on its prototype chain) must have a key of
Symbol.iterator
Attributes. It is a parameterless function, and its return value is an object conforming to the iterator protocol.

When an object needs to be iterated (such as being placed in a

for...of
Loop), first of all, it will be called without parameters
Symbol.iterator
Method, and then use the iterator returned by this method to get the value to be iterated.

It is worth noting that when this zero-argument function is called, it will be called as a method on an iterable object. Therefore, inside the function,

this
Keywords can be used to access the properties of the iterable object to determine what to provide during the iteration.

This function can be a normal function or a generator function to return an iterator object when called. Inside this generator function, you can use

yield
Provide each entry.

Iterator Protocol

The iterator protocol defines a standard way of generating a series of values, whether finite or infinite. When the value is limited, after all the values have been iterated, a default return value will be returned.

Only one with the following semantics is implemented

next()
Method, an object can become an iterator:

Attributesvalue
next
A parameterless function that returns an object that should have the following two properties:
done
(Boolean) If the iterator can produce the next value in the sequence, then
false
. (This is equivalent to not specifying
done
This attribute. ) If the iterator has iterated through the sequence, then
true
. In this situation,
value
It is optional. If it still exists, it is the default return value after the iteration ends.
value
Any JavaScript value returned by the iterator. Can be omitted when done is true.
next()
The method must return an object, which should have two properties:
done
with
value
, If a non-object value is returned (such as
false
or
undefined
), it will throw a
TypeError
abnormal(
"iterator.next() returned a non-object value"
).
//Iterator example function makeIterator ( array ) { let nextIndex = 0 ; return { next : function () { return nextIndex <array.length? { value : array[nextIndex++], done : false }: { done : true }; } }; } let it = makeIterator([ 'yo' , ' yah ' ]); console .log(it.next().value); //'yo' console .log(it.next().value); //'yah' console .log(it.next().done); //trueCopy code

The following are the iterators in class:

class SimpleClass { constructor ( data ) { this .data = data } [ Symbol .iterator]() { //Use a new index for each iterator. This makes multiple //iterations over the iterable safe for non-trivial cases, //such as use of break or nested looping over the same iterable. let index = 0 ; return { next : () => { if (index < this .data.length) { return { value : this .data[index++], done : false } } else { return { done : true } } } } } } const simple = new SimpleClass([ 1 , 2 , 3 , 4 , 5 ]) for ( const val of simple) { console .log(val) //'1' '2' '3' '4' '5' } Copy code

Generator

The generator object is returned by a generator function, and it conforms to the iterable protocol and iterator protocol.

//Example function * gen () { yield 1 ; yield 2 ; yield 3 ; } the let G = Gen (); //"Generator {}" copy the code

Tips

The generator object is both an iterator and an iterable object, because it conforms to the iterable protocol and iterator protocol:

let aGeneratorObject = function * () { yield 1 ; yield 2 ; yield 3 ; }(); typeof aGeneratorObject.next; //returns "function", because there is a next method, so this is an iterator typeof aGeneratorObject[ Symbol .iterator]; //returns "function", because there is a Symbol.iterator method, so this is an iterable object aGeneratorObject[ Symbol .iterator]() === aGeneratorObject; //returns true, because the Symbol.iterator method returns itself (ie iterator), so this is a well-formed iterable object [...aGeneratorObject]; //return [1, 2, 3] Console .log ( the Symbol .iterator in aGeneratorObject) //returns true, because Symbol.iterator aGeneratorObject is an attribute copy the code

From above, we can also use

for...of
To iterate over the generator object:

function * fibonacci () { //A generator function let [prev, curr] = [ 0 , 1 ]; for (;;) { //while (true) { [prev, curr] = [curr, prev + curr]; yield curr; } } for ( let n of fibonacci()) { console .log(n); //Jump out of the loop when n is greater than 1000 if (n >= 1000 ) break ; } Copy code

ES2016

Compared to ES2015, ES2016 only made minor version updates, such as arrays

includes
Methods and exponent operators
**
.

Array.prototype.includes

includes
The method is used to determine whether an array contains a specified value, according to the situation, if it contains, it returns true, otherwise it returns false.

//Example const array1 = [ 1 , 2 , 3 ]; console .log(array1.includes( 2 )); //expected output: true const pets = [ 'cat' , 'dog' , 'bat' ]; console .log(pets.includes( 'cat' )); //expected output: true Console .log (pets.includes ( 'AT' )); //Output expected: to false copy the code

Compared to

Array.prototype.indexOf
,
includes
Can be queried in the array
NaN
, That is to say
includes
You can determine whether the array contains
NaN
.

[ . 1 , 2 , NaN3 ] .includes ( NaN3 ); //to true copy the code

includes
You can also pass in the second parameter:
fromIndex
, It will
formIndex
As the index to search for, query the target value later:

//If fromIndex is greater than or equal to the length of the array, false will be returned and the array will not be searched. [ 1 , 2 , 3 ].includes( 3 , 3 ); //false //If fromIndex is negative, the calculated index will be the position to start searching for searchElement. If the calculated index is less than 0, the entire array will be searched. [ . 1 , 2 , . 3 ] .includes ( . 3 , - . 1 ); //to true copy the code

Exponent operator

as

+
,
-
,
*
,
/
Like common operators, there are special operators for exponentiation:
**
. Compared to
Math.pow()
, The exponent operator is more convenient:

2 ** 10 //1024 copy the code

ES2017

Object.values

Object.values
The method returns an array of all enumerable property values of a given object itself.

Example// const obj = { foo : 'bar' , baz : 42 is }; Console .log ( Object .values (obj)); //[ 'bar', 42 is] copy the code

Object.entries

Object.entries
The method returns an array of key-value pairs for the enumerable properties of the given object itself.

//Example const obj = { foo : 'bar' , baz : 42 }; console .log( Object .entries(obj)); //[['foo','bar'], ['baz', 42] ] Copy code

Thus, it can be used in this way

for...of
To iterate over an object:

const object1 = { a : 'somestring' , b : 42 }; for ( const [key, value] of Object .entries(object1)) { console .log( ` ${key} : ${value} ` ); } //"A: someString" //"B: 42 is" copy the code

You can also convert Object into a Map object:

const obj = { foo : "bar" , baz : 42 }; const map = new Map ( Object .entries(obj)); console .log(map); //Map {foo: "bar", baz: 42} Copy code

String.prototype.padStart/Sting.prototype.padEnd

padStart/padEnd
The method fills the current string with another string so that the resulting string reaches the given length.
padStart
Is filled from the left,
padEnd
Fill it from the right.

const str1 = '5' ; Console .log (str1.padStart ( 2 , '0' )); //"05" Console .log (str1.padEnd ( 2 , '0' )); //"50" copy the code