Like a small partner point a like collection of bai, thank ♥
A, let
The let keyword is used to declare variables. Variables declared using let have several characteristics:
- Duplicate declarations are not allowed
- Block level scope
- There is noVariable ascension(Not allowed before declaring variables)
- The scope chain is not affected
Application scenario: Use let to declare variables in the future
Second, the const
The const keyword is used to declare constants. Const declarations have the following characteristics:
- You have to assign an initial value
- Use uppercase for general constants (unspoken rule)
- Duplicate declarations are not allowed
- The value of constants cannot be modified
- Block level scope
Ps: The modification of object attributes and array elements does not count as the modification of constants, and will not report errors
Application scenario: Declare an object or array type using const. Select let for non-object array type declaration
3. Deconstructive assignment of variables
ES6 allows you to extract values from arrays and objects and assign values to variables in a pattern called deconstructed assignment.
// Array destruct assignment
const xhd = [Su Youpeng.Nicky Wu.'Chen Zhipeng'];
let [ su, wu, chen ] = xhd;
Copy the code
// Destruct assignment of an object
const guo = {
name: 'Guo Degang'.age: '47'.xiangsheng: function () {
console.log("I can speak crosstalk."); }};let { name, age, xiangsheng } = guo;
xiaopin();
Copy the code
Ps: Frequent use of object methods, array elements, can use destruct assignment
4. Template string
Template strings are enhanced strings, marked by backquotes (‘), and have the following characteristics:
- A newline character can appear in a string
// Define a string
let str = ` < ul > < li > Shen Teng < / li > < li > Mary < / li > < li > wei zifeng < / li > < li > Allen < / li > < / ul > `;
Copy the code
- Variable stitching
let lovest = 'cruel';
let out = `${lovest}O 'hara less!!!!! `;
Copy the code
Ps: Use template strings when concatenating strings with variables
Five, simplify the object writing
ES6 allows variables and functions to be written directly inside curly braces as object properties and methods. It’s much more concise.
let name = 'Tencent Games';
let change = function(){
console.log('No money for a hammer!! ');
}
const school = {
name,
change,
pay(){
console.log("Money makes you stronger."); }}Copy the code
Anyway, the shorthand is right
Arrow function
ES6 allows functions to be defined using arrows (=>)
/ / format
let fn = (a,b) = > {
return a + b;
}
// Call the function
let result = fn(1.2);
Copy the code
Note:
- This is static. This always refers to the value of this in the scope in which the function was declared
- Cannot be instantiated as a construct object
- Arguments variables cannot be used
- If the parameter has only one, the parentheses can be omitted
let fn2 = num= > {
return num * 10;
};
Copy the code
- If there is only one statement, the curly braces can be omitted, the return must be omitted, and the function returns the result of the statement
let pow = n= > n * n;
Copy the code
Ps: The arrow function does not change the this pointer, so specifying the callback function is quite appropriate
Rest parameters
ES6 introduces the rest argument, which gets arguments to functions, instead of arguments
// how ES5 gets arguments
function date(){
console.log(arguments);
}
date('giao'.'Ow force to give'.'is dubious);
/ / rest parameters
function date2(. args){
console.log(args);// filter some every map
}
date2('giao'.'Ow force to give'.'is dubious);
// Rest must be placed at the end of the argument
function fn(a,b,... args){
console.log(a);
console.log(b);
console.log(args);
}
fn(1.2.3.4.5.6);
Copy the code
The PS: REST parameter is ideal for scenarios where there are an indefinite number of parameter functions
Extend operators
“…” The extension operator unpacks an array by converting it to a comma-separated sequence of arguments, like the reverse of the REST argument
// Expand the array
const she = ['Selina'.'Hebe'.'Ella'];
function superstar(){
console.log(arguments); } superstar(... she);// chunwan('Selina','Hebe','Ella')
// 1. Array merge
const kuaizi = ['Wang Taili'."Xiao"];
const fenghuang = ['chenrui'.'ling flowers'];
// ES5 array merge
// const zuixuanxiaopingguo = kuaizi.concat(fenghuang);
const zuixuanxiaopingguo = [...kuaizi, ...fenghuang];
// 2. Array clone
const tuhai = ['8'.'5'.'7'];
const sanyecao = [...tuhai];/ / [' 8 ', '5', '7']
//3. Convert the pseudo-array to a real array
const divs = document.querySelectorAll('div');
const divArr = [...divs];
Copy the code
Nine, Symbol
- The basic use
ES6 introduces a new primitive data type, Symbol, that represents unique values. It is the seventh data type of the JavaScript language and is a string-like data type. (1) The value of Symbol is unique and is used to resolve naming conflicts. (2) The value of Symbol cannot be computed with other data. (3) The object attributes defined by Symbol cannot be used for… In loops through, but you can use reflect.ownkeys to get all the key names of the object
/ / create a Symbol
let s = Symbol(a);// console.log(s, typeof s);
// Add the Symbol to the Symbol
let s2 = Symbol('Hey hey hey');
let s3 = Symbol('Hey hey hey');
/ / Symbol. For creation
let s4 = Symbol.for('La la la la');
let s5 = Symbol.for('La la la la');
Copy the code
Ps: Think of Symbol when encountering unique scenes
Symbol Means of adding properties and methods to an object
// Add the method up down to the object
let game = {
name:tetris.up: function(){},
down: function(){}};// Declare an object
let methods = {
up: Symbol(),
down: Symbol()
};
game[methods.up] = function(){
console.log("I can change shapes.");
}
game[methods.down] = function(){
console.log("I can fall fast!!");
}
/ / call
game[methods.up]();
game[methods.down]();
Copy the code
let youxi = {
name:"Werewolf kill."[Symbol('say')]: function(){
console.log("I may speak.")},Symbol('zibao')]: function(){
console.log('I can blow myself up.'); }}Copy the code
-
Symbol built-in value
In addition to defining the Symbol values you use, ES6 provides 11 built-in Symbol values that point to methods used within the language and are automatically executed in certain scenarios.
Symbol value | introduce |
---|---|
Symbol.hasInstance | This method is called when another object uses the instanceof operator to determine whether it is an instanceof that object |
Symbol.isConcatSpreadable | Object Symbol. IsConcatSpreadable attribute is a Boolean value that is equal to the said that the object is used to Array. The prototype. The concat (), whether can be expanded. |
Symbol.species | This property is used when a derived object is created |
Symbol.match | When str.match(myObject) is executed, if the property exists, it is called, returning the return value of the method |
Symbol.replace | When this object is called by the str.replace(myObject) method, the return value of that method is returned |
Symbol.search | When this object is called by the str.search (myObject) method, the return value of that method is returned |
Symbol.split | When this object is called by the str.split(myObject) method, the return value of that method is returned |
Symbol.iterator | Object for… The Symbol. Iterator method is called during the of loop, returning the default traverser for the object |
Symbol.toPrimitive | This method is called when the object is converted to a value of the original type, returning the corresponding value of the original type of the object |
Symbol. toStringTag | When the toString method is called on this object, the return value of the method is returned |
Symbol. unscopables | This object specifies which attributes are excluded from the with environment when the with keyword is used |
Iterators
Iterators are one mechanism. It is an interface that provides a unified access mechanism for various data structures. Any data structure can be iterated by deploying the Iterator interface. (1) ES6 created a new traversal command for… The of loop is an Iterator interface for… Of consumption (for.. In traversal saves the key name, for.. Iterator: iterator: iterator: iterator: iterator: iterator: iterator: iterator
- . Array
- Arguments
- Set
- Map
- String
- TypedArray
- NodeList
(3) Working principle 1. Create a pointer object pointing to the start of the current data structure 2. The first time the object’s next method is called, the pointer automatically points to the first member of the data structure. The next method is then called repeatedly, moving the pointer back until it points to the last member, 4. Each call to the next method returns an object containing the value and done attributes
// Declare an array
const xiyou = ["Tang's monk.Sun Wukong.'Pig Eight Quit'.'沙僧'];
// Create a pointer object
let iterator = xiyou[Symbol.iterator]();
// Call the next method of the object
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
Copy the code
Custom traversal data
// Declare an object
const banji = {
name: "giao".stus: [
'yahou'.'zmsn'.'huohua'.'nosmoking'
],
[Symbol.iterator]() {
// Index variable
let index = 0;
return {
next: () = > {
if (index < this.stus.length) {
const result = {value: this.stus[index], done: false};
// subscript increment
index++;
// Return the result
return result;
} else {
return {value: undefined.done: true}; }}}; }}// Iterate over the object
for (let v of banji) {
console.log(v);
}
Copy the code
Xi. Generators
Generator functions are a kind of asynchronous programming solution provided by ES6. They are special functions with completely different syntactic behavior from traditional functions.
function * gen(){
// console.log(111);
yield 'One without an ear';
// console.log(222);
yield 'One without a tail';
// console.log(333);
yield 'That's strange';
// console.log(444);
}
let iterator = gen();
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
/ / traverse
// for(let v of gen()){
// console.log(v);
// }
Copy the code
Description:
- There is no limit to the location of the **
- The result returned by the generator function is an iterator object, whose next method is called to yield the value
- Yield is equivalent to a pause mark for a function, or you can think of it as a separator for a function, executing one piece of code each time the next method is called
- The next method can pass arguments as the return value of the yield statement
// Generator function arguments
function * gen(arg){
console.log(arg); // AAA
let one = yield 111;
console.log(one); // BBB
let two = yield 222;
console.log(two); // CCC
let three = yield 333;
console.log(three); // DDD
}
// Perform the fetch iterator object
let iterator = gen('AAA');
console.log(iterator.next());
// The next method can take arguments
console.log(iterator.next('BBB'));
console.log(iterator.next('CCC'));
console.log(iterator.next('DDD'));
Copy the code
Twelve, Promise
Promise is a new solution to asynchronous programming introduced in ES6. Syntactically, a Promise is a constructor that encapsulates an asynchronous operation and can retrieve its success or failure, solving callback hell.
// Instantiate the Promise object
const p = new Promise(function(resolve, reject){
setTimeout(function(){
//
let data = 'User data in the database';
resolve(data);
// let err = 'data read failed ';
// reject(err);
}, 1000);
});
// Call the then method of the Promise object
p.then(function(value){
console.log(value);
}, function(reason){
console.error(reason);
})
Copy the code
Promise encapsulates the read file
//1. Import fs module
const fs = require('fs');
//2. Call the method to read the file
/ / fs. ReadFile ('. / resources for learning. The md ', (err, data) = > {
// // If it fails, an error is thrown
// if(err) throw err;
// // If there are no errors, output the content
// console.log(data.toString());
// });
//3. Use the Promise wrapper
const p = new Promise(function(resolve, reject){
fs.readFile(". / resources/learn. Md. "".(err, data) = >{
// Determine if it fails
if(err) reject(err);
// If successful
resolve(data);
});
});
p.then(function(value){
console.log(value.toString());
}, function(reason){
console.log("Read failed!!");
});
Copy the code
Promise. Prototype. Then method
The result of the then method is a Promise object whose state is determined by the execution result of the callback function
// Create a Promise object
const p = new Promise((resolve, reject) = >{
// Asynchronous tasks
setTimeout(() = >{
resolve('User data');
// reject(' reject ');
}, 1000)});// Call the then method
const result = p.then(value= > {
console.log(value);
//1. Non-promise type property, state is success, return value is the object's success value
return 'iloveyou';
/ / 2. Promise
return new Promise((resolve, reject) = >{
// resolve('ok');
reject('error');
});
/ / 3. Wrong
// throw new Error('fuck! ');
throw 'Wrong! ';
}, reason= >{
console.warn(reason);
});
Copy the code
Chain calls
p.then(value= >{
}).then(value= >{});Copy the code
Case – Read multiple files
// Import the fs module
const fs = require("fs");
// Call back to hell
/ / fs. ReadFile ('. / resources for learning. The md ', (err, data1) = > {
/ / fs. ReadFile ('. / resources/planting poems. The md ', (err, data2) = > {
/ / fs. ReadFile ('. / resources/books inductive. Md ', (err, data3) = > {
// let result = data1 + '\r\n' +data2 +'\r\n'+ data3;
// console.log(result);
/ /});
/ /});
// });
// Promise
const p = new Promise((resolve, reject) = > {
fs.readFile(". / resources/learn. Md. "".(err, data) = > {
resolve(data);
});
});
p.then(value= > {
return new Promise((resolve, reject) = > {
fs.readFile("./resources/ heptacter.md".(err, data) = > {
resolve([value, data]);
});
});
}).then(value= > {
return new Promise((resolve, reject) = > {
fs.readFile("./resources/ park is not worth it.md".(err, data) = > {
/ / pumped
value.push(data);
resolve(value);
});
})
}).then(value= > {
console.log(value.join('\r\n'));
});
Copy the code
Promise. Prototype. Catch method
The callback specified by the catch method catches an error thrown by promise
const p = new Promise((resolve, reject) = >{
setTimeout(() = >{
// Set the state of the p object to failure and set the value of failure
reject("What's the matter!);
}, 1000)});// p.then(function(value){}, function(reason){
// console.error(reason);
// });
p.catch(function(reason){
console.warn(reason);
});
Copy the code
13, the Set
ES6 provides a new data structure called a Set. It is similar to an array, but the values of its members are unique. Collections implement the Iterator interface, so you can use “extension operators” and “for… of…” For traversal, properties and methods of the collection:
- Size returns the number of elements in the collection
- Add adds a new element and returns the current collection
- Delete Deletes the element and returns Boolean
- Has checks whether the collection contains an element, returning Boolean
- Clear Clears the collection and returns undefined
// Declare a set
let s = new Set(a);let s2 = new Set(['1'.'2'.'3'.'4'.'2']);
// Number of elements
// console.log(s2.size);
// Add a new element
// s2.add('5');
// Delete elements
// s2.delete('4');
/ / testing
// console.log(s2.has('6'));
/ / to empty
// s2.clear();
// console.log(s2);
for(let v of s2){
console.log(v);
}
Copy the code
Of course, sets can also be array de-duplication, intersection, union, difference set
let arr = [1.2.3.4.5.4.3.2.1];
//1. Array decrement
// let result = [...new Set(arr)];
// console.log(result);
/ / 2. The intersection
let arr2 = [4.5.6.5.6];
// let result = [...new Set(arr)].filter(item => new Set(arr2).has(item));
// console.log(result);
/ / 3. And set
// let union = [...new Set([...arr, ...arr2])];
// console.log(union);
4 / / difference set
let diff = [...new Set(arr)].filter(item= >! (new Set(arr2).has(item)));
console.log(diff);
Copy the code
14, the Map
ES6 provides Map data structures. It is similar to an object, but also a collection of key-value pairs. However, the scope of “keys” is not limited to strings; all types of values (including objects) can be used as keys. Map also implements the Iterator interface, so you can use “extension operators” and “for… of…” I’m going to iterate. Map attributes and methods:
- Size Returns the number of Map elements
- Set adds a new element that returns the current Map
- Get returns the key value of the keyname object
- Has checks whether the Map contains an element, returning Boolean
- Clear Clears the collection and returns undefined
/ / declare the Map
let m = new Map(a);// Add elements
m.set('name'.'blame pigeons');
m.set('say'.function(){
console.log("Let us not be afraid of any difficulties.");
});
let key = {
hobby : 'winter'
};
m.set(key, ['come on'.'Olidhi'.'Dry and done']);
// size
// console.log(m.size);
/ / delete
// m.delete('name');
/ / to get
// console.log(m.get('hobby'));
// console.log(m.get(key));
/ / to empty
// m.clear();
/ / traverse
for(let v of m){
console.log(v);
}
Copy the code
15, Class
ES6 provides a more traditional language approach, introducing the concept of Class as a template for objects. With the class keyword, you can define a class. Basically, ES6 classes can be seen as a syntactic candy that does most of what ES5 does. The new class writing method simply makes object prototype writing clearer and more like object-oriented programming syntax.
/ / cell phone
function Phone(brand, price){
this.brand = brand;
this.price = price;
}
// Add method
Phone.prototype.call = function(){
console.log("I can call!!");
}
// instantiate the object
let Huawei = new Phone('huawei'.5999);
Huawei.call();
console.log(Huawei);
//class
class Shouji{
// The constructor name cannot be changed
constructor(brand, price){
this.brand = brand;
this.price = price;
}
// Methods must use this syntax and cannot use ES5's full object form
call(){
console.log("I can call!!"); }}let onePlus = new Shouji("1 +".1999);
console.log(onePlus);
Copy the code
Static members
1. The instance object does not have the properties and methods of the constructor object, so there is no communication between them and the prototype object of the constructor. Properties in a function object that belong to the function object, not to the instance object, are called static members
// Constructor object
function Phone(){}// Static member
Phone.name = 'mobile phone';
Phone.change = function(){
console.log("I can change the world");
}
// Prototype object properties
Phone.prototype.size = '5.5 inch;
// Instance object
let nokia = new Phone();
console.log(nokia.name); // undefinded
// nokia.change(); // not a function
console.log(nokia.size); / / 5.5 inch
Copy the code
class
/ / class
class Phone{
// Static attributes
static name = 'mobile phone';
static change(){
console.log("I can change the world"); }}// Instance object
let nokia = new Phone();
console.log(nokia.name); // undefined
console.log(Phone.name); / / cell phone
Copy the code
Properties and methods of static annotations are classes, not instance objects
Class inheritance
// ES5
function Phone(brand, price){
this.brand = brand;
this.price = price;
}
Phone.prototype.call = function(){
console.log("I can make a call.");
}
// Smart phone
function SmartPhone(brand, price, color, size){
// Inherits the parent class
Phone.call(this, brand, price);
this.color = color;
this.size = size;
}
// Sets the prototype of the child constructor
SmartPhone.prototype = new Phone;
SmartPhone.prototype.constructor = SmartPhone;
// Declare the method of the subclass
SmartPhone.prototype.photo = function(){
console.log("I can take pictures.")
}
SmartPhone.prototype.playGame = function(){
console.log("I can play games.");
}
const huawei = new SmartPhone('huawei'.2499.'black'.'5.5 inch);
console.log(huawei);
Copy the code
Class inheritance and method rewriting
// ES6
class Phone{
// constructor
constructor(brand, price){
this.brand = brand;
this.price = price;
}
// Member attributes of the parent class
call(){
console.log("I can call!!"); }}class SmartPhone extends Phone {
// constructor
constructor(brand, price, color, size){
super(brand, price);Call (this, brand, price)
this.color = color;
this.size = size;
}
photo(){
console.log("Photos");
}
playGame(){
console.log("Play the game");
}
// Method override
call(){
console.log('I can make a video call.'); }}const xiaomi = new SmartPhone('millet'.1999.'black'.'4.7 inch);
// console.log(xiaomi);
xiaomi.call();
xiaomi.photo();
xiaomi.playGame();
Copy the code
Get and set
Get encapsulates the dynamic properties of an object, and SET controls and determines whether it is valid
/ / get and set
class Phone{
get price() {console.log("The price attribute was read.");
return 'iloveyou';
}
set price(newVal) {console.log('The price attribute has been modified'); }}// instantiate the object
let s = new Phone();
// console.log(s.price);
s.price = 'free';
Copy the code
16. Numerical extension
- Number.EPSILON is the minimum precision of the JavaScript representation
/ / EPSILON attribute's value is close to 2.2204460492503130808472633361816 e-16
function equal(a, b){
if(Math.abs(a-b) < Number.EPSILON){
return true;
}else{
return false; }}// console.log(0.1 + 0.2 === 0.3);
console.log(equal(0.1 + 0.2.0.3))
Copy the code
- Binary and octal ES6 provides a new way to write binary and octal values, represented by the prefixes 0b and 0o, respectively.
let b = 0b1010;
let o = 0o777;
let d = 100;
let x = 0xff;
console.log(x);
Copy the code
- Number.isFinite tests whether a Number isFinite
- Number.isNaN tests whether a value isNaN
- ParseInt Number.parseFloat The string is converted to an integer
- Number.isInteger Determines whether a Number is an integer
- Math.trunc erases the decimal part of a number
- Math.sign determines whether a number is positive or negative, and returns 1 for positive, -1 for negative, and 0 for zero
Object extension
- Object.is compares whether two values are strictly equal, basically the same as the “===” behavior (+0 and NaN)
console.log(Object.is(120.120));// true
console.log(Object.is(NaN.NaN));// true
console.log(NaN= = =NaN);// false
Copy the code
- Object.assign merge, which copies all the enumerable properties of the source Object to the target Object
const config1 = {
host: 'localhost'.port: 3306.name: 'root'.pass: 'root'.test: 'test'
};
const config2 = {
host: 'http://baidu.com'.port: 33060.name: 'baidu.com'.pass: 'iloveyou'.test2: 'test2'
}
console.log(Object.assign(config1, config2)); // config2 overrides config1
Copy the code
- Object.setprototypeof Sets the prototype Object. Object.getprototypeof gets the prototype Object
const school = {
name: 'lanxiang'
}
const cities = {
xiaoqu: ['Beijing'.'shandong'.'shenzhen']}Object.setPrototypeOf(school, cities); // Make cities the prototype object for school
console.log(Object.getPrototypeOf(school)); // Get the school prototype object
Copy the code
Xviii. Modularization
Modularity refers to taking a large program file, breaking it up into many smaller files, and then putting the smaller files together.
Benefits:
Name conflict prevention, code reuse, high maintainability
Grammar:
The function of the module consists of two commands: export and import. The export command is used to specify the external interface of a module, and the import command is used to input functions provided by other modules.
What questions are welcome to discuss in the comments section o~♥
-
Author: Capricorn when the wind blows
-
Source/Origin: Wind Time Capricorn’s “Puge – Flying Team -ES6 Summary”
-
The copyright of this article belongs to the author and nuggets jointly, welcome to reprint, and give the original link in the obvious position of the article page, without the consent of the author must retain this statement, otherwise reserve the right to pursue legal responsibility.