Hello everyone, I am Nezha. Without further words, today I bring you an article entitled ES6 comprehensive summary essential for front-end interview. Welcome to enjoy it.Copy the code
preface
Learn the basics of ES6, understand what ECMAScript Outlines are, understand the Symbol data type, understand let and const, deconstruct variable assignments, Set and Map.
What are arrow functions, what are ES6 extensions to ES5, and some advanced operations in ES6?
In order to facilitate my study, I made a mind map, as shown below:
ESMAScript overview
ECMAScript is a scripting programming language known as JavaScript or JScript. It is called ECMAScript in Chinese and European Computer Manufacturers Association Script in English. We can call it ES6 for short. It is widely used on the World Wide Web.
ECMAScript is a standardized specification for a scripting language developed by Brandon Ek of Netscape, originally named Mocha, later changed to LiveScript, and finally renamed JavaScript.
In December 1995, Sun and Netscape jointly released JavaScript. In November 1996, Netscape submitted JavaScript to the European Computer Manufacturers Association for standardization. The first version of ECMA-262 was adopted by the ECMA organization in June 1997.
ECMA Script is the name of the ecMA-262 standardized scripting language. Although JavaScript and JScript are ECMAScript compatible, they contain capabilities beyond ECMAScript.
ECMAScript is an object-based programming language that performs computations in the host environment and manipulates computable objects. ECMAScript was originally designed as a Web scripting language to support dynamic presentation of Web pages and provide server-side computing power for a Web-based client-server architecture.
As a scripting language, ECMAScript has the same properties as other scripting languages: “to manipulate, customize, and automate functionality provided by an existing system.”
What is the relationship between ECMAScript and JavaScript?
To simplify life, ECMAScript is the international standard for the JavaScript language, and JavaScript is the implementation of ECMAScript.
Symbol data type
ES6 introduces a new primitive data type, Symbol, which represents a unique value and is used to define unique object attribute names.
The interpretation of Symbol
Symbol data type:
- Definition of Symbol;
- Symbol is the object property name;
- Symbol Use scenario;
- Symbol.
The definition of the Symbol
- A Symbol type can be generated by using the Symbol() function;
- The Symbol() function can take a string as an argument
Sample code:
let s1 = Symbol('web');
let s2 = Symbol('web');
console.log(s1 === s2);
console.log(typeof s1);
console.log(typeof s2);
Copy the code
Chrome screenshots:
It can be seen from the figure that the Symbol() function receives the same parameters, and the values of its variables are different. S1 and S2 are variables of Symbol type. Because the values of the variables are different, the printed result is false. Typeof is used to get the corresponding type, so the printed result is symbol.
Symbol is the object property name
Symbol can be used as an object property name in three ways.
- The first:
Sample code:
let symbol = Symbol();
let a = {};
a[symbol] = 'web';
Copy the code
First, declare a variable Symbol of type Symbol, an empty object is a, through a[Symbol] to the object a value of a web string. Represents Symbol as the object property name and Web as its property value.
- The second:
Sample code:
let symbol = Symbol();
let a = {
[symbol]:'web'
};
Copy the code
[Symbol] : [Symbol] : [Symbol] : [Symbol] : [Symbol] : [Symbol]
- The third:
Sample code:
let symbol = Symbol();
let a = {};
Object.defineProperty(a, symbol, {value: 'web'});
Copy the code
We first declare a variable Symbol of type Symbol, an empty Object called A, and assign a web string to Object A via object.defineProperty ().
The value of Symbol, as the object property name, cannot be used with the dot operator.
Use of Symbol
One has two usage scenarios:
- Because the value of Symbol is not equal, the value of Symbol type is the object property name and does not duplicate.
- The code forms a strong coupling to some concrete string.
The Symbol for
Through Object. GetOwnPropertySymbols () method, which can get all the Symbols of specified Object attribute names.
Let and const
- Let is a keyword defined in the ES6 specification for declaring variables.
- Variables declared using let have a block-level scope.
Why do you need block-level scopes?
The reason for adding this block-level scope is to understand the problems that occur when ES5 does not have block-level scope.
- Scenario one is that the inner variables may override the outer variables.
- Scenario 2 is that variables declared in an if or for loop leak out as global variables.
Scene 1:
Scene 2:
Code examples:
if(true) { var web = 'web'; } console.log(web); // The web is accessible without an iF blockCopy the code
The premise of block-level scope is let variable declaration
- An independent pair of braces, between which is the block-level scope of the variable.
- The block-level scope of a variable is enclosed in a pair of braces for condition statements, function declarations, loops, and so on.
Const declares a read-only constant. Const Once a constant is declared, its value cannot be changed.
Const and let are valid only within the declared block-level scope. Otherwise, an error will be reported.
A constant declared by the const command can only be used after the declared position.
A constant declared by const, which, like let, cannot be declared repeatedly.
Destruct assignment of variables
In ES6, you can extract values from arrays and objects and assign values to variables, called deconstructed assignment.
Deconstructed assignment means that as long as the pattern on both sides of the equal sign is the same, the variable on the left will be assigned the corresponding value.
Sample code:
let [x,y='b'] = ['a'];
console.log(y); // b
let [x,y='b'] = ['a', undefined];
console.log(y); // b
let [x,y='b'] = ['a', null];
console.log(y); // null
Copy the code
Deconstructing assignment classification:
- Destruct assignment of arrays
- Object destructuring assignment
- Destruct assignment of a string
- Number and Boolean deconstruction assignment
- Destruct assignment of function arguments
Deconstruct the assignment case
There are two cases:
- Completely deconstruction
- Incomplete deconstruction
Incomplete deconstruction
The code is as follows:
let [a = 1, b] = [];
// a = 1, b = undefined
Copy the code
Destruct assignment of arrays
The code is as follows:
let [a, [b], d] = [1, [2, 3], 4];
a // 1
b // 2
d // 4
Copy the code
Destruct assignment allows you to specify default values.
The code is as follows:
let [foo = true] = [];
foo // true
Copy the code
When using the default value, use undefined because undefined cannot be assigned.
The code is as follows:
let [x = 1] = [undefined];
x // 1
let [x = 1] = [null];
x // null
Copy the code
Object to deconstruct
The code is as follows:
let { bar, foo } = { foo: 'aaa', bar: 'bbb' };
foo // "aaa"
bar // "bbb"
let { baz } = { foo: 'aaa', bar: 'bbb' };
baz // undefined
Copy the code
By destructuring, we can easily copy the methods of objects to variables.
The code is as follows:
const { log } = console;
log('hello') // hello
Copy the code
Or:
const { log:minelog } = console;
minelog ('hello') // hello
Copy the code
When we use destruct assignment, we need to be aware of the scope of declared variables:
// let x; {x} = {x: 1}; // let x; ({x} = {x: 1});Copy the code
In the array is a special object
let arr = [1, 2, 3];
let {0 : first, [arr.length - 1] : last} = arr;
first // 1
last // 3
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
Deconstructing defaults
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
String deconstruction
A string itself is also an object, sometimes deconstructed as an array
The code is as follows:
const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"
Copy the code
Deconstruct as an object
let {length : len} = 'hello';
len // 5
Copy the code
Residual operator
let [a, ...b] = [1, 2, 3];
//a = 1
//b = [2, 3]
Copy the code
Destruct assignment of function arguments
function add([x, y]){ return x + y; } add([1, 2]); / / 3Copy the code
Calculate the sum of any parameters of the function:
Code:
function sum(... num){ var sumNum = 0; for(let i=0; i<num.length; i++){ sumNum += parseInt(num[i]) } console.log(sumNum) }Copy the code
The Set and Map
A Set is similar to an array, but the values of its members are unique and have no duplicate values.
A Set uses the add() method to add elements. No duplicate values are added, so a Set can deduplicate arrays.
A Map is like an object, and the value of the key name can be of various types.
The statement
- Use the new Set() constructor to declare a Set;
- Use the new Map() constructor to declare a Map.
Use for… Of iterates through the values in the array
Operation method
Common methods: Delete Delete, has whether to delete, clear Clear. The addition to a Set is add(), while Map is Set and get.
Has is used to determine whether a Set or Map contains elements.
Set can be used to add or modify elements in a Map, which only Map has.
Traversal methods
There are keys, values, entries, forEach.
Keys gets all keys, values gets all values, entries gets all keys and values, and forEach iterates through all keys and values.
Arrow function
ES6 uses the arrow function (=>) to define functions.
Arrow function with arguments
Code:
var single = a => a
single('web')
Copy the code
Arrow function with no arguments
Code:
var log = () => {
alert('web')
}
Copy the code
Arrow function with multiple arguments
Code:
Var add = (a,b) => a+b (1,2)Copy the code
Es6 extends es5
There are three main types:
- Extension of a function
- Object extension
- Extension of arrays
Extension of a function
Extensions of es6 functions include: default values, residual operators, and extension operators.
The default value
In es5, the function of the default value is set, through the “| |” to carry on the set, when the function parameter is undefine, take the default values.
In ES6, the default value of a function is written after the parameter definition.
A code example is as follows:
// es5
function log(x,y) {
y = y || 'web';
console.log(x,y);
}
function log(x,y="web"){
console.log(x,y);
}
Copy the code
Residual operator
The remaining operators represent statements:… Arrr stands for parameters, specifying that multiple parameters can be specified.
A code example is as follows:
function web(... arr) { for(let item of arr) { console.log(item); }} web,3,4,5,6 (1);Copy the code
Extended operator
Example code is as follows:
function add(a,b,c) { console.log(a); console.log(b); console.log(c); } var arr = [1,2,3]; add(... arr);Copy the code
Object extension
- Es6 allows you to write variables and functions directly to objects as properties and methods.
- Expressions are allowed as attributes of objects in ES6, and function names can be defined in the same way.
- Setter and getter. JavaScript object properties are made up of names, values, and a set of properties.
Object manipulation in ES6:
Object.is() : compares whether two values are equal. Object.assign() : Used to merge objects. Object. GetOwnPropertyDescriptor: return to the description of the Object properties. Object.keys() returns an array containing all the enumerable properties of the Object itself.
Extension of arrays
CopyWithin (target,start,end) : Within the current array, copies the member at the specified location to another location, and then returns the current array.
Target indicates the place from which data is replaced. If it’s negative, it’s reciprocal.
Start indicates that data is read from this location. The default value is 0. If it is negative, it is the reciprocal.
End means to stop reading data until that point, which is equal to the array length by default. If it is negative, it is reciprocal.
Find () represents the array member used to find the first symbolic condition.
FindIndex () returns the location of the first eligible array member, or -1 if all members fail.
Fill () means to fill an array, and the fill() method is used to initialize an empty array.
Includes () : this method returns a Boolean value indicating whether an array contains a given value.
Es6 Advanced operations
The Promise object is used to indicate the final state, completion or failure, of an asynchronous operation.
Promise is a solution to asynchronous programming by presenting asynchronous operations as a flow of synchronous operations, avoiding the problem of multiple layers of nested callback functions.
A Promise has several states:
pending
The initial state is neither a success state nor a failure state.fulfilled
The operation succeeds.rejected
The operation fails.
When either of these conditions occurs, the handler for the Promise object’s then() method binding is called.
The then() method contains two parameters, onfulfilled and onRejected, which are both function types.
This is a big pity. When the Promise is fulfilled, the onfulfilled then() method will be called. When the Promise is fulfilled, the onfulfilled THEN () method will be called.
The promise.prototype. then and promise.prototype. catch methods return Promise objects, so they can be called chained.
Iterator
An Iterator is an interface that provides a unified access mechanism for various data structures.
Any data structure that deploys the Iterator interface can be iterated.
Iterator does:
- Provides a unified, easy access interface for various data structures.
- Allows the members of a data structure to be arranged in some order.
- ES6 created a new traversal command for… Of circulation.
Primitive data structures with Iterator interfaces, arrays, some array-like objects, Set structures and Map structures.
Generator
Generator is an asynchronous programming solution provided by ES6. Syntactically, it can be thought of as a state machine that encapsulates multiple states internally.
Execute Generator, which generates and returns an traverser object. Iterator object that traverses each state of the Generator function in turn.
The Generator function is a generic function.
First, there is an asterisk between the function keyword and the function name.
Second, the body of a function uses yield expressions to iterate over the state.
The code is as follows:
function* newGenerator() {
yield 'web';
yield 'it';
return 'ending';
}
Copy the code
The code understands that after executing a Generator function, it is not immediately executed and returns a pointer to the internal state rather than the result of the function’s execution.
Move the pointer to the Next state using the Next() method of the traverser object. Each time the next() method is called, the internal pointer executes from the function head or where it last stopped until the next yield expression position is reached.
The Generator executes in segments, the yield expression is a pause flag, and the next() method can resume execution.
The next() function takes an argument that returns the last yield expression, since yield itself does not return a value.
Class
ES6 introduces the concept of Class classes, which can be defined using the Class keyword.
Sample code:
class Person { constructor(name,age){ this.name = name; this.age = age; } say () {return 'name: + enclosing the name +' age ', enclosing the age + "age"; } } var obj = new Person('web',12); console.log(obj.say());Copy the code
Simple data types
There are 5 simple data types in ES5: Undefined, Null, Boolean, Number, String.
Set
- Members cannot be duplicated
- Just keys, no keys, kind of like an array.
- You can iterate through it with methods like add, delete,has
Set instance properties
- Constructor: a constructor
- Size: number of elements
The code is as follows:
let set = new Set([1, 2, 3, 2, 1])
console.log(set.length) // undefined
console.log(set.size) // 3
Copy the code
Set instance method
Operation method
- Add (value) : adds a value, which is equivalent to push in an array
- Delete (value) : deletes the value in the collection
- Has (value) : Determines whether a value exists in the set
- Clear () : Clears the collection
Traversal methods
- Keys () : Returns an iterator containing all the keys in the collection
- Values () : Returns all worthy iterators in a containing collection
- Entries () : Returns a key-value iterator containing all the elements of the Set object
- ForEach (callbackFn, thisArg) : Used to perform callbackFn operations on collection members
Map
- It’s essentially a set of key-value pairs, sort of a set
- You can iterate, you can do a lot of things and you can convert to a lot of different data formats
Set and Map are mainly used in data reorganization and data storage
A Set is a data structure called a collection, and a Map is a data structure called a dictionary
Map attributes and methods
Properties:
- Constructor: a constructor
- Size: Returns the number of elements contained in the dictionary
The code is as follows:
const map = new Map([
['name', 'web'],
['des', 'JS']
]);
map.size // 2
Copy the code
Operation method:
- Set (key, value) : Adds a new element to the dictionary
- Get (key) : Finds a specific value by key and returns it
- Has (key) : Checks whether the key exists in the dictionary
- Delete (key) : removes the corresponding data from the dictionary by key
- Clear () : Removes all elements from this dictionary
Traversal methods
- Keys() : Returns all key names contained in the dictionary as iterators
- Values () : Returns all values contained in the dictionary as iterators
- Entries () : Returns an iterator for all members
- ForEach () : Traverses all the members of the dictionary
Dictionary (Map)
Differences between sets and dictionaries:
- Common: Collections and dictionaries can store values that are not duplicated
- Differences: Collections store elements as [value, value], dictionaries as [key, value]