当前位置:网站首页>Esmascript 6.0 advanced
Esmascript 6.0 advanced
2022-06-09 05:26:00 【Classmate Tao Ran.】
Catalog
1.3 Function parameter name default
1.5Map data structure (Map aggregate )
1.6Set data structure (Set aggregate )
1.8rest Parameters ( Shape parameter ...)
1.9 Extension operator ( Actual parameters ...)
2.2ES6 module Implicit requirements
2.4 The default is derived export default
1. Advanced Grammar
1.1 Variable declarations
keyword | Whether there is Variable Promotion | Whether there is Temporary dead zone | Whether to allow Repeat statement | Whether to allow Reassign | Whether to allow only Declaration does not assign value |
var | There is | non-existent | allow | allow | allow |
let | non-existent | There is | Don't allow | allow | allow |
const | non-existent | There is | Don't allow | Don't allow | Don't allow |
- var
//1 var Declared variables , Can improve
{
var a = 10;
}
console.info(a); //10
//2 Allow duplicate statements
var b = 20;
var b = 30;
console.info(b); //30
//3 Allow reassignment
b = 40;
console.info(b); //40
//4 It is allowed to declare only non assignment
var c;
console.info(c); //undefinedlet
//1 let Declared variables , Variable promotion not allowed
/*
{
let a = 10;
}
console.info(a); // abnormal , a is not defined
*/
//2 There is a temporary dead zone : In block code , All variables are local variables ( Must declare first , Reuse )
/*
var b = 10;
{
console.info(b); //b is not defined
let b = 20;
}
*/
//3 Duplicate statements are not allowed
/*
var c = 10;
let c = 20; //Identifier 'c' has already been declared ( Variable c It has been declared that )
*/
/**/
//4 Allow reassignment
let d = 10;
d = 20;
console.info(d); //20
//5 It is allowed to declare only non assignment
let e;
console.info(e); //undefined- const
const a = 10;
//1. No lifting is allowed
/*
{
const b = 10;
}
console.info(b) //b is not defined
*/
//2. There is a temporary dead zone
/*
var c = 10;
{
console.info(c) //c is not defined
const c = 20;
}
*/
//3. Duplicate statements are not allowed
/*
const a = 20; //Identifier 'a' has already been declared
*/
//4. Reassignment is not allowed
/*
a = 20; //Assignment to constant variable.
*/
//5. It is not allowed to declare only non assignment
//const d; // Missing initializer in const declaration1.2 Deconstruct assignment
- ES6 Allow to follow certain mode , Extract values from arrays and objects , Assign values to variables , This is called deconstruction (Destructuring)
- ES5 Syntax for getting object data , as follows :
const people = {
name: 'lux',
age: 20
}
const name = people.name; //ES5 How to write it
const age = people.age;
console.log(name + ' ‐‐‐ ' + age)- Object to deconstruct : Parse multiple attributes from an object to different variables at once
- Deconstructed variable names , Must be consistent with property name .
var person = {
username : "jack",
password : "1234",
"show" : function(){
console.info("show Yes ");
},
course : {
en : 100,
math : 99
}
}
//es5 Get data
console.info( person.username )
console.info( person.password )
person.show()
// Object to deconstruct
let {username,password,show, age } = person;
console.info(username) //jack
console.info(password) //1234
console.info( show ) //[Function: show]
console.info( age ) //undefined
show(); //show Yes
// Objects in structure objects
let {course} = person;
console.info(course) //{ en: 100, math: 99 }
let {course : {en, math}} = person;
console.info(en) //100- An array of deconstruction : Assign values in order of array order
// Declaration array
var arr = [' jiangsu ',' Suqian '];
// Deconstruct members from an array
let [province, city] = arr;
console.info(province)
console.info(city)
// In exchange for 2 A variable
let x = 10;
let y = 20;
console.info(`x = ${x} , y = ${y}`);
[y,x] = [x,y];
console.info(`x = ${x} , y = ${y}`);- Common applications : Traverse Map ( Explain later )
var map = new Map();
map.set('first', 'hello');
map.set('second', 'world');
for (let [key, value] of map) {
console.log(key + " is " + value);
}
// first is hello
// second is world- Common applications : Module content extraction ( Explain later )
const { SourceMapConsumer, SourceNode } = require("source-map");1.3 Function parameter name default
- When declaring function parameters , Set default values for parameters
function log(x, y = 'World') { //y Parameter setting defaults
console.log(x, y);
}
log('Hello') // Hello World
log('Hello', 'China') // Hello China
log('Hello', '') // Hello- Default and deconstruction
function fun1({x = "x1" , y } = {y : "y2"}){
return [x , y] ;
}
console.info( fun1() ); //[ 'x1', 'y2' ]
console.info( fun1({}) ); //[ 'x1', undefined ] ,
//{} Cover {y:"y2"} , Deconstruct default ,x=x1,y=undefined
- Default values apply : Parameter is required
function fun2(args = new Error(" Parameters must be filled in ")){
console.info(args);
}
fun2();
fun2("abc");1.4 Arrowhead function this
- this object :
- function Function this Represents the current object
- Arrow function does not have its own this, Arrowhead function this See if there's a function in the outer layer ,
- If there is , Of outer functions this It's the function of the inner arrow this,
- without , In a browser environment this yes window; stay node.js Environment is the specified environment ( for example :vue)
- establish demo03_2.js file
var name=" external ";
var user = {
name : ' Inside ',
show : function(){
console.info(this.name)
},
show2 : () => {
console.info(this.name)
console.info(user.name)
}
}
user.show() // Inside
user.show2() //undefined、 Inside - establish demo03_3.html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
</body>
</html>
<script>
var name=" external ";
var user = {
name : ' Inside ',
show : function(){
console.info(this.name)
},
show2 : () => {
console.info(this.name)
console.info(user.name)
}
}
user.show() // Inside
user.show2() // external 、 Inside ( On the browser side ,this Express window)
</script>1.5Map data structure (Map aggregate )
- JavaScript The object of (Object), It's essentially a set of key value pairs (Hash structure ), But traditionally only strings are used as keys . This has brought a great limit to its use .
- 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 .
1.6Set data structure (Set aggregate )
- ES6 Provides a new data structure Set. It's like an array , But the values of the members are unique , There are no duplicate values .
//Set aggregate : Store unique data
var set = new Set();
set.add(1);
set.add(2);
set.add(3);
set.add(2);
set.add(1);
console.info( set ); //Set { 1, 2, 3 }- Filter the duplicate data in the array
var arr = [2, 3, 5, 4, 5, 2, 2];
// The way 1
var set2 = new Set();
// 1) Traversal array , Add data to set
arr.map( s => set2.add(s) );
// 2) Traverse set aggregate , Add to new array
var arr2 = [];
set2.forEach( v => arr2.push(v) );
console.info( arr2 ); //[ 2, 3, 5, 4 ]
// The way 2
var arr3 = [ ... new Set(arr) ]
console.info( arr3 ); //[ 2, 3, 5, 4 ]1.7for...of Traverse
- stay JavaScript in , There are many ways to traverse data , stay ES6 Provided in for…of , Used to unify the traversal of all data structures .
// Prepare the data
var arr4 = ['x','y','z'];
var map4 = new Map();
map4.set("a","1111");
map4.set("b","2222");
map4.set("c","3333");
var set4 = new Set();
set4.add("m");
set4.add("n");
set4.add("L");
var obj4 = {
name : "jack",
password : "1234"
}- for…of Traverse
// for ... of
for(let a of arr4){ // Traversal array
console.info(a);
}
for(let [k,v] of map4){ // Traverse Map,for…of Traversal in combination with deconstruction Map
console.info(` The output data key is ${k} The value is ${v}`);
}
for(let s of set4){ // Traverse Set
console.info(s);
}
for(let key of Object.keys(obj4)){ // Custom objects cannot traverse , Need help keys convert to “ Key array ”
console.info(` The key of the object is ${key}, The value is ${obj4[key]}`);
}
for(let [k,v] of Object.entries(obj4)){// You can also use entries convert to “ Key value pair ”
console.info(`entries : The key of the object is ${k}, The value is ${v}`);
}
// Add : Custom objects are handled specially ([Symbol.iterator]) You can also traverse , But there is bug, Imperfect , Refer to the following :
let obj = {
// The original content
length: 3,
[Symbol.iterator]: Array.prototype[Symbol.iterator]
}- JS The traversal already in
Traverse the way | describe | example |
for Loop traversal | Normal cycle , It's often used to handle arrays | for (let i = 0;i < array.length;i++){ |
map() | Array chain operation function | array.map( fn ).xxx() |
forEach() | Simplify arrays 、Map、Set The traversal | xxx.forEach( fn ) |
for…in | Traversing an object's enumerable properties in any order | for(let xx in obj) {} |
for…of | Different data structures provide a unified access mechanism | for(let xx of obj) {} |
- map Use of functions
//map function , Convert an array to a new array
//var New array = Old array .map( Processing function ); // Every element in the old array , All will pass “ Processing function ” To deal with
// example : Will array ['a','b','c'] Convert to string 'cba'
var m = arr4.map( s => {
return s.toUpperCase();
}).reverse().join(",");
console.info(m);- forEach Use of functions
//forEach Traverse
arr4.forEach(s => { // Traversal array
console.info(s);
});
map4.forEach( (k,v)=> { // Traverse Map
console.info(`${k} ${v}`);
});
set4.forEach( k => { // Traverse Set
console.info( k ) ;
});
//obj4.forEach(); // I won't support it - for…in Traversing objects
for(let prop in obj4){
console.info( prop + "," + obj4[prop]);
}1.8rest Parameters ( Shape parameter ...)
- rest Parameters , Namely JS Variable parameters of . Before the last variable in the parameter list , Use “...”
Function name ( Parameters 1, Parameters 2, … variable )function add(...num){ // Variable parameters num, It's an array , The runtime stores all the arguments
var sum = 0 ;
num.forEach( i => sum += i);
return sum;
}
console.info( add(1,2,3) );
function count(args,...other){
console.info(arguments.length); // Although there are the number of parameters , Pseudo array , Out of commission forEach Traversal
console.info(other.length); // Number of variable parameters , True array , have access to forEach Traversal
}
count(1,2,3);1.9 Extension operator ( Actual parameters ...)
- Extension operator (spread) Three points (...). It's like rest Inverse operation of parameter ,
- The operation data is an array , Convert an array to a comma separated sequence of parameters .
- The operation data is the object , Take out all traversable properties of parameter object , Copy to current object
var arr = ['a','b','c'];
function fun3(x,y,z){
console.info( [x,y,z] );
}
fun3( arr ); //[ [ 'a', 'b', 'c' ], undefined, undefined ]
fun3( ...arr ); //[ 'a', 'b', 'c' ]
let z = { a: 3, b: 4 };
let n = { ...z }; // { a: 3, b: 4 }2. modularization
- stay ES6 Before ,JavaScript There has been no module (module) system , Cannot split a large program into interdependent small files , Put them together in a simple way .
- stay ES6 Before , The community offers some solutions , There are two main kinds :CommonJS and AMD
2.1ES5 CommonJS Solution
- CommonJS A server-side solution (commonsJs Can be in node.js function )
- CommonJS Need a compatible script loader , To support require and module.exports function , For module import and export .
- Node.js Support this idea
- Module export
module.exports = (a,b)=> a+b;- Module import
let add = require("./demo07_1");
console.info( add(1,2) );2.2ES6 module Implicit requirements
- ES6 Strict mode is adopted automatically in the module of , Whether or not you add "use strict";.
- The strict model mainly has the following limitations .
Variables must be declared before they can be used
A parameter of a function cannot have a property with the same name , Otherwise, the report will be wrong
Out of commission with sentence
Cannot assign to read-only property , Otherwise, the report will be wrong
Cannot use prefix 0 Represents octal number , Otherwise, the report will be wrong
Properties that cannot be deleted cannot be deleted , Otherwise, the report will be wrong
Cannot delete variable delete prop, Will report a mistake , Only attributes can be deleted delete global[prop]
eval It doesn't introduce variables in its outer scope
eval and arguments Cannot be reassigned
arguments Does not automatically reflect changes in function parameters
Out of commission arguments.callee
Out of commission arguments.caller
prohibit this Point to global object
Out of commission fn.caller and fn.arguments Get the stack of function calls
Reserved words added ( such as protected、static and interface)
2.3ES6 module
- A module , It is a file that exposes its properties or methods to other modules .
- ES6 The module consists of two commands :export and import.
- export command : Specify the external interface of the module . One export Statement declare once , There can be more than one file .
- import command : Import other modules .
2.4 The default is derived export default
- Use import Command loading module , You must know the variable name or function name in the module , Otherwise, we can't load .
- For the convenience of using the module , Module allows to use export default Define default output . Only one default output is allowed for a module .
- Default export variables
边栏推荐
- How WPS ppt pictures come out one by one
- 【IT】福昕pdf保持工具选择
- AI video cloud: a good wife in the era of we media
- Windows10 installs both MySQL 5 and MySQL 8
- Common interview questions
- 基础集群部署 - kubernetes-simple
- Intranet penetration hash delivery attack
- 模式识别大作业——PCA&Fisher&KNN&Kmeans
- What did we do from March to April?
- Kube dns yaml
猜你喜欢

MarathonLb的负载研究

2022 tea artist (intermediate) examination question simulation examination question bank and simulation examination

application. Properties mysql. cj. jdbc. Driver red

queue

Alibaba cloud AI training camp - machine learning 2:xgboost

Alibaba cloud AI training camp - machine learning 3:lightgbm

Simple process and problem handling of cmdbuilding

Heap and priority queues

A few minutes to understand the Flink waterline

Alibaba cloud AI training camp - SQL basics 4: set operation - addition and subtraction of tables, join, etc
随机推荐
Apache Devlake 代码库导览
queue
三方账号授权登录系统设计思路
2022焊工(初级)特种作业证考试题库及模拟考试
Data Summit 2022 大会资料分享(共23个)
How WPS ppt pictures come out one by one
Differences between tinyint and int
Analysis of countdownlatch source code of AQS
Codeigniter3 learning notes 5 (form verification)
FPGA based TDC Research Report
myql报错 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column
Lighting - 光的亮度衰减
Pull down the new project code and make it red
AQS 之 CyclicBarrier 源码分析
2022 tea artist (intermediate) examination question simulation examination question bank and simulation examination
array
validate-npm-package-name
2021 national vocational skills competition Liaoning "Cyberspace Security Competition" and its analysis (ultra detailed)
pytest_ Introduction to allure priority and fixture scope parameters
Youshimu V8 projector opens the "vision" field of high fresh