当前位置:网站首页>Ecmascript6 new features
Ecmascript6 new features
2022-06-22 23:47:00 【Delete your code in the middle of the night·】
ECMAScript6 New characteristics
let keyword
let The keyword is used to declare variables , Use let Declared variables have several characteristics :
(1) Duplicate statements are not allowed
(2) Block level scope
(3) No variable promotion
const keyword
const The keyword is used to declare constants ,const The statement has the following characteristics
(1) The declaration must be given an initial value
(2) Duplicate statements are not allowed
(3) Value cannot be modified
(4) Block level scope
notes : Object attribute modification and array element change will not trigger const error
Application scenarios : Declare object types using const, Non object type declaration option let
Deconstruction and assignment of variables
ES6 Allows you to extract values from arrays and objects according to certain patterns , Assign values to variables , This is called deconstruction assignment .
// Deconstruction and assignment of arrays
const arr = [' Jacky Cheung ',' Lau Andy ',' The dawn ',' Aaron Kwok '];
let [zhang, liu, li, guo] = arr;
// Object's deconstruction assignment
const lin = {
name: ' Lin Zhiying ',
tags: [' Driver ',' singer ',' Little whirlwind ',' actor ']
};
let wangfei = {
name: ' Faye Wong ',
age: 18,
songs: [' Red bean ',' Fleeting years ',' ambiguous ',' legend '],
history: [
{name: ' Dou Wei '},
{name: ' Li Yapeng '},
{name: ' Nicholas Tse '}
]
};
let {songs: [one, two, three], history: [first, second, third]} = wangfei;notes : Frequent use of object methods 、 Array elements , You can use the deconstruction assignment form
Template string
Template string (template string) It's an enhanced string , Use back quotes (`) identification
characteristic :(1) A newline character can appear in the string
(2) have access to ${xxx} Formal output variable
let str = `<ul>
<li> Shen Tang </li>
<li> Ma Li </li>
<li> Wei Xiang </li>
<li> Allen </li>
</ul>`;
let star = ' Wang Ning ';
let result = `${star} In the last few years, he left happy fried dough twist. `;In case of string and variable splicing, use template string
Simplify object writing
ES6 Allow in braces , Write variables and functions directly , Properties and methods as objects . This kind of writing is more concise .
let name = ' Community security ';
let eat = ' Bear biscuits ';
let hobby = function(){
console.log(' I'm a community security guard , Love bear cookies ');
}
// Attribute and method abbreviations
let intro = {
name,
eat,
hobby,
change(){
console.log(' To change the world ');
}
}Arrow function
ES6 Allow to use arrow (=>) Defined function
1. General writing method
let fn = (a, b) => {
return a + b;
}
Note on arrow function :
(1) Arrow function this Points to the scope under which the declaration is located this Value
(2) Arrow functions cannot be instantiated as constructors
(3) There is no arrow function arguments
(4) If there is only one parameter , Then brackets can be omitted
(5) If there is only one statement in the function body , The curly braces can be omitted , The return value of the function is the execution result of the statement
The arrow function does not change this The direction of , So it is very suitable for setting and this Unrelated callbacks , For example, array callback 、 Timer callback , Not suitable for event callbacks and object methods .
rest Parameters
ES6 introduce rest Parameters , To get arguments to a function , Used in place of arguments
rest Parameter is very suitable for the scenario of variable number parameter function
// The functions and arguments similar
function add(...args){
console.log(args);
}
add(1,2,3,4,5);
//rest Parameter must be the last formal parameter
function minus(a, b, ...args){
console.log(a,b,args);
}
minus(100,1,2,3,4,5,19)spread Extension operator
Extension operator (spread) Also three points (...). It's like rest Inverse operation of parameter , Convert an array to a comma separated sequence of parameters , Unpack the array .
// Expand array
let movies = [' Smell and know women ', ' Touch and ', ' Green paper '];
function fn(){
console.log(arguments);
}
fn(...movies)
// Expand the object
let first = {
f: ' first '
};
let second = {
s: ' the second '
};
let third = {
t: ' Third '
};
let all = { ...first, ...second, ...third };Symbol
Basic use :ES6 A new type of raw data is introduced Symbol, Represents a unique value . It is Javascript The seventh data type of language , Is a data type similar to a string .
Symbol characteristic
(1)Symbol Value of is unique , Used to resolve naming conflicts
(2)Symbol Value cannot be calculated with other data
// establish Symbol
let s1 = Symbol();
console.log(s1, typeof s1);
// Add marked Symbol
let s2 = Symbol(' Little flower ');
let s2_2 = Symbol(' Little flower ');
console.log(s2 === s2_2);
// Use Symbol for Definition
let s3 = Symbol.for(' tearful ');
let s3_2 = Symbol.for(' tearful ');
console.log(s3 === s3_2);Symbol The only reasonable use of type is to store with variables symbol Value , Then use the stored values to create object properties .
Symbol Built in values
In addition to defining what you use Symbol Out of value ,ES6 It also provides 11 Built in Symbol value , Point to methods used within a language .
Symbol.hasInstance | When other objects use instanceof Operator , When judging whether it is an instance of the object , Will call this method |
Symbol.isConcatSpreadable | Object's Symbol.isConcatSpreadable Property is equal to a Boolean value , Indicates that the object is used for Array.prototype.concat() when , Can I expand . |
Symbol.unscopables | This object specifies the use of with When a keyword , Which attributes will be with Environmental exclusion . |
Symbol.match | When executed str.match(myObject) when , If the attribute exists , It will call it. , Returns the return value of the method . |
Symbol.replace | When the object is str.replace(myObject) Method call , Will return the return value of the method . |
Symbol.search | When the object is str. search (myObject) Method call , Will return the return value of the method . |
Symbol.split | When the object is str. split (myObject) Method call , Will return the return value of the method . |
Symbol.iterator | Object to carry out for...of loop , Would call Symbol.iterator Method , Returns the default traversal of the object |
Symbol.toPrimitive | When the object is converted to a value of the original type , Will call this method , Returns the original type value of the object . |
Symbol. toStringTag | Call... On this object toString When the method is used , Returns the return value of the method |
Symbol.species | When creating a derived object , Will use this property |
iterator
iterator (Iterator) It's an interface , Provide unified access mechanism for different data structures . Any data structure only needs to be deployed Iterator Interface , You can complete the traversal operation .
(1)ES6 Creates a new traversal command for...of loop ,Iterator Interface z Mainly for for...of consumption
(2) Original possession Iterator Interface data ( You can use for...of Traverse )
a)Array
b)Arguments
c)Set
d)Map
e)String
f)TypedArray
g)NodeList
(3) working principle
1. Create a pointer object , Point to the start of the current data structure
2. The first time an object is called next Method , The pointer automatically points to the first member of the data structure
3. Next, call next Method , The pointer moves all the way back , Until it points to the last member
4. Every call next Method returns a containing value and done Object of property
When you need to customize the traversal data , Think of iterators
Set
ES6 Provides a new data structure Set( aggregate ). It's like an array , But the values of members are unique , The collection is implemented iterator Interface , So you can use Extension operator and for...of Traversal , Properties and methods of a collection :
(1)size Returns the number of elements in the collection
(2)add Add a new element , Returns the current collection
(3)delete Remove elements , return Boolean value
(4)has Detect whether the collection contains an element , return Boolean value
(5)clear Empty the set , return undefined
// Create an empty set
let s = new Set();
// Create a non empty collection
let s1 = new Set([1,2,3,1,2,3]);
// Collection properties and methods
// Returns the number of elements in the collection
console.log(s1.size);
// Add a new element
console.log(s1.add(4));
// Remove elements
console.log(s1.delete(1));
// Check whether a value exists
console.log(s1.has(2));
// Empty the set
console.log(s1.clear());Map
ES6 Provides Map data structure , It's like an object , It's also a set of key value pairs , however “ key ” Is not limited to strings , Various types of values ( Including objects ) Can be used as a key .Map It has also been realized. iterator Interface , So you can use 『 Extension operator 』 and 『for…of…』 Traversal .Map Properties and methods of :
- size return Map Number of elements of
- set Add a new element , Returns the current Map
- get Returns the key value of the key name object
- has testing Map Is there an element in , return boolean value
- clear Empty the set , return undefined
// Create an empty map
let m = new Map();
// Create a non empty map
let m2 = new Map([
['name',' Silicon Valley '],
['slogon',' Continuously improve industry standards ']
]);
// Properties and methods
// Get the number of mapping elements
console.log(m2.size);
// Add mapping values
console.log(m2.set('age', 6));
// Get mapping value
console.log(m2.get('age'));
// Detect whether there is this mapping
console.log(m2.has('age'));
// eliminate
console.log(m2.clear());
class class
ES6 Provides a more traditional approach , Introduced Class( class ) The concept , Template as object . adopt class keyword , Classes can be defined . Basically ,ES6 Of class Can be seen as just a grammar sugar , Most of its functions ,ES5 Can do it , new class The writing method is just to make the writing method of the object prototype clearer 、 It's more like the syntax of object-oriented programming .
Knowledge point :
- class Declaration class
- constructor Define constructor initialization
- extends Inherited parent class
- super Call the parent constructor
- static Define static methods and properties
- Parent class methods can override
// Parent class
class Phone {
// Construction method
constructor(brand, color, price) {
this.brand = brand;
this.color = color;
this.price = price;
}
// Object methods
call() {
console.log(' I can call !!!')
}
}
// Subclass
class SmartPhone extends Phone {
constructor(brand, color, price, screen, pixel) {
super(brand, color, price);
this.screen = screen;
this.pixel = pixel;
}
// Subclass method
photo(){
console.log(' I can take pictures !!');
}
playGame(){
console.log(' I can play games !!');
}
// Method rewriting
call(){
console.log(' I can make video calls !!');
}
// Static methods
static run(){
console.log(' I can run programs ')
}
static connect(){
console.log(' I can establish a connection ')
}
}
// Instantiate objects
const Nokia = new Phone(' nokia ', ' gray ', 230);
const iPhone6s = new SmartPhone(' Apple ', ' white ', 6088, '4.7inch','500w');
// Call subclass method
iPhone6s.playGame();
// Call the override method
iPhone6s.call();
// Call static methods
SmartPhone.run();
Numerical expansion
1) Binary and octal
Binary system 0b octal 0o Decimal system 0x
2) Number.isFinite() And Number.isNaN()
Number.isFinite() Used to check whether a value is finite
Number.isNaN() Used to check whether a value is NaN
3)Number.parseInt() And Number.parseFloat()
ES6 Take a global approach parseInt and parseFloat, Migration to Number The above object , Use the same .
4) Math.trunc
Used to remove the decimal part of a number , Returns the integer part .
5) Number.isInteger
Number.isInteger() Used to determine whether a numerical value is an integer
Object extension
ES6 Some new Object Object method
- Object.is Compare two values to see if they are strictly equal , And 『===』 The behavior is basically the same (+0 And NaN)
- Object.assign Merge of objects , All enumerable properties of the source object , Copy to target object
- __proto__、setPrototypeOf、 setPrototypeOf You can set the prototype of the object directly
边栏推荐
猜你喜欢

Leakcanary source code (2)

China Mobile's mobile phone users grow slowly, but strive for high profit 5g package users

Flutter outsourcing, undertaking flutter project

C sqlsugar, hisql, FreeSQL ORM framework all-round performance test vs. sqlserver performance test

The breakthrough of key chips hindering Huawei 5g mobile phones has been achieved, and domestic chips have gained 10% share

'dare not doubt the code, but have to doubt the code 'a network request timeout analysis

事务系统的隔离级别

OJ daily practice - spanning 2020

昆仑分布式数据库独特的变量读写功能介绍

xml转义字符对照表
随机推荐
Future alternatives to IPv4! Read the advantages, features and address types of IPv6
C sqlsugar, hisql, FreeSQL ORM framework all-round performance test vs. sqlserver performance test
OJ daily practice - word length
14. 最长公共前缀
在一条DML语句中插入/更新/删除/获取几百万行数据,你会特别注意什么?
Array and string offset access syntax with curly braces is no longer support
Sword finger offer 07 Rebuild binary tree
MySQL8.0轻松完成GTID主从复制
Do domestic mobile phones turn apples? It turned out that it was realized by 100 yuan machine and sharp price reduction
PHP7.3报错undefined function simplexml_load_string()
Web Caching Technology
OJ每日一练——跨越2020
从类、API、框架三个层面学习设计可复用软件的具体技术学习心得
为什么现在大家都不用外键了(二)?
Uniapp modifies array properties, and the view is not updated
Use the find command
OJ每日一练——单词的长度
Programmers' choice of taking private jobs and part-time jobs
Anti shake & throttling enhanced version
flink同步mysql数据到ES