Today we will review the new grammar of ES6

Let and const

  1. Lets are only valid within code blocks, var is valid globally
  2. Let cannot repeat declarations, var can
  3. Let is suitable for a for loop
  4. Let does not have variable promotion, var does
  5. Const must be initialized when declaring a constant
  6. Const guarantees that the data in the memory address to which the variable points remains unchanged, not that the value of the variable remains unchanged.
  7. Const temporary dead: If there is a let or const declaration in a code block, the code block will have a closed scope for those declared variables from the beginning of the code block, and an error will be reported if the variable is used within the code block before being declared
var PI = "a"; if (true) { console.log(PI); // ReferenceError: Cannot access "PI" const PI = "3.1415926"; } ----------------------------- var str = "Hi!" ; if (true) { console.log(str); // ReferenceError: Cannot access "STR" before initialization let STR = "Hello World! ; }Copy the code

2. Deconstruct assignment

  1. Deconstruct source: right side of expression
  2. Deconstruct target: left side of expression
  3. Destruct target = Destruct source
  4. Array deconstruction:
let [a, [[b], c]] = [1, [[2], 3]];
// a = 1
// b = 2
// c = 3
---------------------------
let [a, , b] = [1, 2, 3];
// a = 1
// b = 3
---------------------------
let [a = 1, b] = []; // a = 1, b = undefined
---------------------------
let [a, ...b] = [1, 2, 3];
//a = 1
//b = [2, 3]
Copy the code
  1. String deconstruction:
let [a, b, c, d, e] = 'hello';
// a = 'h'
// b = 'e'
// c = 'l'
// d = 'l'
// e = 'o'
Copy the code
  1. Destruct defaults:let [a = 2] = [undefined]; // a = 2The default value is triggered only if the match result is not undefined
  2. Object deconstruction:

basic

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

Can be nested and ignored

let obj = {p: ['hello', {y: 'world'}};let {p: [x, { y }] } = obj;
// x = 'hello'
// y = 'world'
let obj = {p: ['hello', {y: 'world'}};let {p: [x, {  }] } = obj;
// x = 'hello'
Copy the code

Incomplete deconstruction

let obj = {p: [{y: 'world'}};let {p: [{ y }, x ] } = obj;
// x = undefined
// y = 'world'
Copy the code

Residual operator

let{a, b, ... rest} = {a: 10, b: 20, c: 30, d: 40}; // a = 10 // b = 20 // rest = {c: 30, d: 40}Copy the code

Deconstruct default values

let {a = 10, b = 5} = {a: 3};
// a = 3; b = 5;
let {a: aa = 10, b: bb = 5} = {a: 3};
// aa = 3; bb = 5;
Copy the code
  1. In fact, deconstructive assignment is to assign the corresponding value on the right to the left in a certain way at one time. Cooperate with… Expansion operators are more aromatic.

Third, the Symbol

  1. The primitive data type Symbol represents a unique value. The largest use of Symbol is to define a unique attribute name for an object.
let sy = Symbol("KK");
console.log(sy);   // Symbol(KK)
typeof(sy);        // "symbol"// The same parameter Symbol() returns different valueslet sy1 = Symbol("kk"); 
sy === sy1;       // false
Copy the code
  1. Symbol is used as the object property name to ensure that the property is not the same name.
let sy = Symbol("key1"); / / write 1let syObject = {};
syObject[sy] = "kk";
console.log(syObject);    // {Symbol(key1): "kk"} // Write method 2let syObject = {
  [sy]: "kk"
};
console.log(syObject);    // {Symbol(key1): "kk"} //let syObject = {};
Object.defineProperty(syObject, sy, {value: "kk"});
console.log(syObject);   // {Symbol(key1): "kk"}
Copy the code
  1. Symbol cannot be used as an object property name. Operator, because the. Operator is followed by a string, you need to use []
  2. The value of Symbol as a property name is public and does not appear in for.. , in the for… Of, will not be the Object. The keys (), Object, getOwnPropertyNames () returns. Through Object. GetOwnPropertySymbols () and Reflect. OwnKeys () to get.
  3. A constant defined with a string will conflict. A constant defined with a Symbol will not
  4. The Symbol defined using the singleton pattern has different values than the Symbol defined using symbol.for (). Symbol.for() first searches globally for the registered Symbol with the string parameter as the name of the Symbol value. If so, returns the Symbol value. If not, creates a new Symbol with the string parameter as the name of the Symbol value and registers it in the global environment for search.
let yellow = Symbol("Yellow"); // Singleton modelet yellow1 = Symbol.for("Yellow");
yellow === yellow1;      // false
 
let yellow2 = Symbol.for("Yellow");
yellow1 === yellow2;     // true
Copy the code

In simple terms, the Symbol. For () definition returns if there is a Symbol corresponding to the string, and creates a new Symbol if there is no Symbol corresponding to the string. The definition of symbol.for () registers the Symbol corresponding to the string in the global environment for later search.

  1. Symbol.keyfor () returns the registered key. Symbol. For(string) returns the same ciphertext as the same key. Symbol. KeyFor (ciphertext) returns the key.

4. Map and Set

Map

  1. Instantiate a Map object with new Map()
  2. Map.set (key, value) sets the key and value of an Object. Unlike Object, the key of a map can be any type. This is the best thing about map objects
  3. Map.get (key) Gets the corresponding value
  4. When NaN is the key, the value is the same (although NaN! ==NaN, but it’s equal here as a key)
  5. Available for.. Of and forEach traversal
var myMap = new Map();
myMap.set(0, "zero");
myMap.set(1, "one"); // Two will be displayedlog. One is the"0 = zero"The other one is"1 = one"
for (var [key, value] of myMap) {
  console.log(key + "="+ value); } -------------------------- // displays two logs. One is the"0 = zero"The other one is"1 = one"
myMap.forEach(function(value, key) {
  console.log(key + "=" + value);
}, myMap)
Copy the code
  1. Map transfers to Array
var kvArray = [["key1"."value1"], ["key2"."value2"]]. Var myMap = new Map(kvArray); // The Map constructor converts a two-dimensional array of key-value pairs into a Map object. Var outArray = array. from(myMap);Copy the code
  1. Map Clone new objects
var myMap1 = new Map([["key1"."value1"], ["key2"."value2"]]); var myMap2 = new Map(myMap1); console.log(myMap1 === myMap2); / / printfalse. The Map object constructor generates an instance, iterating out new objects.Copy the code
  1. Map Merge objects
var first = new Map([[1, 'one'], [2, 'two'], [3, 'three']]); var second = new Map([[1,'uno'], [2, 'dos']]); Uno, DOS, three var merged = new Map([...first,...second]); uno, DOS, three var merged = new Map([...first,...second]);Copy the code

Set

  1. Set objects allow you to store unique values of any type, whether raw values or object references.
  2. Several special identical cases:
    • Plus 0 is the same thing as minus 0
    • Undefined is the same as undefined
    • NaN is not equal to NaN, but only one can be stored in a Set
  3. A set holds only values
  4. New Set() instantiates the Set object
  5. Set.add (value) Adds values
  6. Set.has (value) Determines whether the value exists
  7. Array = set […] is available… Turn the set into an array

5. String

  1. Includes () determines whether the parameter string is found
  2. StartsWith () determines whether the argument string is at the head of the original string.
  3. EndsWith () determines whether the argument string is at the end of the original string.
  4. Both of these take a second argument, the starting search position, return Boolean, and cannot be passed a regular expression
let string = "apple,banana,orange";
string.includes("banana");     // true
string.startsWith("apple");    // true
string.endsWith("apple");      // false
string.startsWith("banana"/ /, 6)true
Copy the code
  1. Repeat () repeats the string a specified number of times and returns
  2. PadStart () and padEnd() return a new string, indicating that the string is completed from the head/tail with an argument string. The first argument is the minimum length of the returned string, and the second argument is the string to be completed with Spaces by default. Often used to complete bits.
console.log("h".padStart(5,"o"));  // "ooooh"
console.log("h".padEnd(5,"o"));    // "hoooo"
console.log("h".padStart(5));      // " h"
Copy the code
  1. Template string ‘, which can define a multi-line string with Spaces and newlines, or add variables to the string with ${variable}
function f() {return "have fun!";
}
let string2= `Game start,${f()}`;
console.log(string2);  // Game start,have fun!
Copy the code
  1. The label template
alert`Hello world! `; // Equivalent to alert('Hello world! ');
Copy the code

Six, objects,

  1. ES6 allows properties of an object to write variables directly, where the property name is the variable name and the property value is the variable value.
const person = {age, name}; Const person = {age: age, name: name}Copy the code
  1. Method can also be abbreviated
const person = {
  sayHi(){
    console.log("Hi"); } // Equal to const person = {sayHi:function(){
    console.log("Hi"); }}Copy the code
  1. The attribute name can be an expression, but it must be included with []. The attribute name and the attribute name abbreviation cannot be used at the same time
const obj = {
 ["he"+"llo"] () {return "Hi"; }}Copy the code
  1. Object extension operator…
let person = {name: "Amy", age: 15};
letsomeone = { ... person }; someone; //{name:"Amy", age: 15} -------------------------- // Merge objectslet age = {age: 15};
let name = {name: "Amy"};
letperson = {... age, ... name}; person; //{age: 15, name:"Amy"}
Copy the code

New methods for objects

  1. Object.assign(target Object, source Object…) Use to copy all enumerable properties of the source object into the target object. Belong to shallow copy.
let target = {a: 1};
let object2 = {b: 2};
letobject3 = {c: 3}; Object.assign(target,object2,object3); // The first argument is the target object, followed by the source object target; / / {2, a: 1, b: c: 3} -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- / / the Object, into the Object before returns Object. The assign (3); // Number {3} typeof Object.assign(3); //"object"
Copy the code
  1. Object.is(value 1, value 2) Compares two values for strict equality (similar to ===)
  2. And ===
Object.is(+0,-0); object.is (+0,-0); //false+ 0 = = = 0 / /trueObject. Is (NaN,NaN); //true
NaN === NaN  //false
Copy the code

Seven, arrays,

  1. Array.of() forms an Array of all the values in the argument as rawconsole.log(Array.of(1, 2, 3, 4)); // [1, 2, 3, 4]
  2. Array.from() converts an array-like object or iterable to an Array. parameterArray.from(arrayLike[,mapFn[,thisArg]])
console.log(Array.from([1, , 3])); // [1, undefined, 3] ------------------------ console.log(Array.from([1, 2, 3], (n) => n * 2)); / / (2, 4, 6] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- / / thisArg is used to specify the map function executes this object.let map = {
    do: function(n) {
        returnn * 2; }}let arrayLike = [1, 2, 3];
console.log(Array.from(arrayLike, function (n){
    returnthis.do(n); }, map)); / / (2, 4, 6]Copy the code

The conversion class array must contain the length attribute. It can also convert maps, sets, and strings

  1. Find () looks for the elements in the array that match the criteria, and if there are more than one, returns the first element.
letarr = Array.of(1, 2, 3, 4); console.log(arr.find(item => item > 2)); / / 3Copy the code
  1. FindIndex () finds the index of the elements in the array that match the criteria, and if there are multiple elements that match the criteria, returns the index of the first element.
letarr = Array.of(1, 2, 1, 3); // Argument 2(optional) : specifies the value of this in the callback function console.log(arr.findIndex(item => item = 1)); / / 0Copy the code
  1. Fill () fills the contents of array elements indexed in a range into a single specified value.
letarr = Array.of(1, 2, 3, 4); // argument 3(optional) : end index to be filled, which defaults to the end of the array console.log(arr.fill(0,1,2)); // [1, 0, 3, 4]Copy the code
  1. CopyWithin () changes an array element indexed in a certain range to an element indexed in another specified range for that array.
// argument 3(optional) : end index of the data to be overridden, which defaults to the end of the array console.log([1, 2, 3, 4].copywithin (0,2,4)); // argument 1: start index of the data to be overridden // argument 3(optional) : end index of the data to be overridden. // [3, 4, 3, 4]Copy the code
  1. Entries () traverses key-value pairs,keys() traverses key names, and values() traverses key values
for(let [key, value] of ['a'.'b'].entries()){ console.log(key, value); } / / 0"a"/ / 1"b"// Do not use for... Of circulationlet entries = ['a'.'b'].entries(); console.log(entries.next().value); / / [0,"a"] console.log(entries.next().value); / / [1,"b"] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --for(let key of ['a'.'b'].keys()){
    console.log(key);
}
// 0
// 1
---------------------------
for(let value of ['a'.'b'].values()){ console.log(value); } / /"a"
// "b"
Copy the code
  1. Includes () looks up whether the array contains a value
// Parameter 1: contains the specified value [1, 2, 3]. Includes (1); //true// Parameter 2: optional, start search index, default is 0 [1, 2, 3].includes(1, 2); //false
Copy the code
  1. Flat () converts a nested array into a one-dimensional array. FlatMap () processes each element before executing flat().
console.log([1 ,[2, 3]].flat()); / / [1, 2, 3] / / specified conversion of nested layers. The console log ([1, [2, [3, [4, 5]]]]. Flat (2)); / / [1, 2, 3, 4, 5]] / / no matter how many layers of nested. The console log ([1, [2, [3, [4, 5]]]]. Flat (Infinity)); / / [1, 2, 3, 4, 5] / / skip automatically open the console log ([1, [2, 3]]. Flat ()); < p > / / [1, 2, 3] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - / / parameter 1: traversal functions, the traversal functions can accept three parameters: the current element, the current element indexes, the original array / / parameter 2: Log ([1, 2, 3].flatmap (n => [n * 2])); / / (2, 4, 6]Copy the code
Refer to theRUNOOB