【Web】ES6 Study Notes

Table of contents

Chapter 1 Introduction to ECMASript

1.1. What is ECMA

insert image description here

The Chinese name of ECMA (European Computer Manufacturers Association) is the European Computer Manufacturers
Association. The goal of this organization is to evaluate, develop and approve telecommunications and computer standards. After 1994 the
organization changed its name to Ecma International.

1.2. What is ECMAScript

ECMAScript is a scripting programming language standardized by Ecma International through ECMA-262.

1.3. Who is maintaining ECMA-262

TC39 (Technical Committee 39) is a committee that promotes the development of ECMAScript. Its members are all
companies (mainly browser manufacturers, including Apple, Google, Microsoft, Intel, etc.). TC39 holds regular
meetings attended by representatives of member companies and invited experts

1.4. Why learn ES6

⚫ The version of ES6 has the most changes and is a milestone
⚫ ES6 has added many new grammatical features, making programming easier and more efficient
⚫ ES6 is a front-end development trend and a must-have skill for employment

Chapter 2 ECMASript 6 New Features

2.1. let keyword

	let a;
	let b,c,d;
	let e = 100;
	let f = 521, g = 'iloveyou', h = [];

The let keyword is used to declare variables. Variables declared using let have several characteristics:
1)Duplicate statement not allowed

	let star = '罗志祥';
	let star = '小猪';	//报错
  1. block scope
	if else while for 
    {
    
    
    	let girl = '周扬青';
    }
   	console.log(girl);	//报错
  1. variable hoisting does not exist
	console.log(song);
	let song = '恋爱达人';	//报错
  1. does not affect the scope chain
	{
    
    
		let school = 'SHOOL';
		function fn(){
    
    
		console.log(school);
		}
		fn();
	}

Application scenario: It is right to use let to declare variables in the future

2.2. The const keyword

The const keyword is used to declare constants, const declarations have the following characteristics

const SCHOOL = 'SCHOOL';
  1. declaration must assign an initial value
	const A;	//报错
  1. Identifiers are generally uppercase
	const a = 100;	//潜规则
  1. Duplicate statement not allowed
	const a = 100;
	const b = 200;`	//报错
  1. Value does not allow modification
	SCHOOL = 'ATGUIGU';	//可以用作常数,如PI
  1. block scope
	{
    
    
        const PLAYER = 'UZI';
    }
  1. For element modification of arrays and objects, it is not counted as modification of constants, and no error will be reported
	const TEAM = ['UZI','MXLG','Ming','Letme'];
	TEAM.push('Meiko');		//不报错

let-practice case

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>点击 DIV 换色</title>
    <link crossorigin="anonymous" href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css"
        rel="stylesheet">
    <style>
        .item {
      
      
            width: 100px;
            height: 50px;
            border: solid 1px rgb(42, 156, 156);
            float: left;
            margin-right: 10px;
        }
    </style>
</head>

<body>
    <div class="container">
        <h2 class="page-header">点击切换颜色</h2>
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>
    </div>
    <script>
        //获取div元素对象
        let items = document.getElementsByClassName('item');

        //遍历并绑定事件
        for(let i = 0;i<items.length;i++){
      
      
            items[i].onclick = function(){
      
      
                //修改当前元素的背景颜色
                // this.style.background = 'pink';
                items[i].style.background = 'pink';
            }
        }
        
    </script>
</body>
</html>

Note: Object property modification and array element change will not trigger const error
Application scenario: declare object type using const, non-object type declaration choose let

2.3. Variable destructuring assignment

ES6 allows to extract values ​​from arrays and objects and assign values ​​to variables according to a certain pattern, which is called destructuring assignment.

  1. Array Destructuring
	const F4 = ['小沈阳','刘能','赵四','宋小宝'];
    let [xiao, liu, zhao, song] = F4;
    console.log(xiao);
    console.log(liu);
    console.log(zhao);
    console.log(song);
  1. object deconstruction
	const zhao = {
    
    
		name: '赵本山',
		age: '不详',
		xiaopin: function(){
    
    
		console.log("我可以演小品");
		}
	};
	let {
    
    name, age, xiaopin} = zhao;
    console.log(name);
    console.log(age);
    console.log(xiaopin);
    xiaopin();
	let {
    
    xiaopin} = zhao;
    xiaopin();

insert image description here

Note: If you frequently use object methods and array elements, you can use the destructuring assignment form

2.4. Template strings

The template string (template string) is an enhanced version of the string, identified by backticks (`), features:

  1. statement
	let str = `我也是一个字符串哦!`;
    console.log(str, typeof str);

insert image description here

  1. Line breaks can appear directly in the content
	let str = `<ul>
    	<li>沈腾</li>
   	 	<li>玛丽</li>
    	<li>魏翔</li>
    	<li>艾伦</li>
    	</ul>`;
    

The output is the same, with newlines:

insert image description here

  1. variable splicing
	let lovest = '魏翔';
	let out = `${
      
      lovest}是我心目中最搞笑的演员!!`;
	console.log(out);

2.5. Simplified object writing

ES6 allows variables and functions to be written directly inside curly braces as properties and methods of objects. This writing is more concise.

	let name = '大表哥';
    let change = function(){
    
    
    	console.log('我可以改变你!!');
    }

    const school = {
    
    
    	name,
    	change,
    	improve(){
    
    
   		 	console.log("我可以提高你的技能");
    	}
     }

     console.log(school);

Note: The shorthand form of the object simplifies the code, so it is right to use the shorthand in the future

2.6. Arrow functions

ES6 allows the use of "arrows" (=>) to define functions.

1.== Declare a function ==

	//普通函数
	let fn = function(a,b){
    
    
		return a + b;
    }
    //箭头函数
    let fn = (a,b) => {
    
    
        return a + b;
    }
  1. Call functions
	let result = fn(1, 2);
    console.log(result);
  1. this is static. this always points to the value of this in the scope where the function is declared
	function getName(){
    
    
    	console.log(this.name);
    }
    //this指向这里
    let getName2 = () => {
    
    
    	console.log(this.name);
    }
	//设置 window 对象的 name 属性
	window.name = '尚硅谷';
		const school = {
    
    
		name: "ATGUIGU"
	}
	//直接调用
    getName();
    getName2();
    //call 方法调用
    getName.call(school);//指向school
    getName2.call(school); //始终指向window

insert image description here

  1. Object cannot be instantiated as a constructor
	let Person = (name, age) => {
    
    
		this.name = name;
		this.age = age;
	}
	let me = new Person('xiao',30);
	console.log(me);

insert image description here

  1. The arguments variable cannot be used
	let fn = () => {
    
    
		console.log(arguments);
	}
	fn(1,2,3);

insert image description here

  1. Shorthand for arrow functions
//1) 省略小括号, 当形参有且只有一个的时候
	let add = n => {
    
    
		return n + n;
	}
//2) 省略花括号, 当代码体只有一条语句的时候, 此时 return 必须省略
	let pow = n => n * n;
        console.log(pow(8));

Note: The arrow function will not change the point of this, which is very suitable for specifying the callback function

Arrow function usage scenarios

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>箭头函数实践</title>
    <style>
        div {
      
      
            width: 200px;
            height: 200px;
            background: #58a;
        }
    </style>
</head>
<body>
    <div id="ad"></div>
    <script>
        //需求-1  点击 div 2s 后颜色变成『粉色』
        //获取元素
        let ad = document.getElementById('ad');
        //绑定事件
        ad.addEventListener("click", function(){
      
      
            //保存 this 的值
            // let _this = this;
            //定时器
            setTimeout(() => {
      
      
                //修改背景颜色 this
                // console.log(this);
                // _this.style.background = 'pink';
                this.style.background = 'pink';
            }, 2000);
        });

        //需求-2  从数组中返回偶数的元素
        const arr = [1,6,9,10,100,25];
        // const result = arr.filter(function(item){
      
      
        //     if(item % 2 === 0){
      
      
        //         return true;
        //     }else{
      
      
        //         return false;
        //     }
        // });
        
        const result = arr.filter(item => item % 2 === 0);

        console.log(result);

        // 箭头函数适合与 this 无关的回调. 定时器, 数组的方法回调
        // 箭头函数不适合与 this 有关的回调.  事件回调, 对象的方法

    </script>
</body>

</html>

2.7. rest parameters

ES6 introduces the rest parameter, which is used to obtain the actual parameters of the function and is used instead of arguments

ES5 way to get actual parameters

	function date(){
    
    
		console.log(arguments);
	}
	date('白芷','阿娇','思慧');
  1. rest parameter
	function date(...args){
    
    
    	console.log(args);// filter some every map 
    }
    date('阿娇','柏芝','思慧');
  1. The rest parameter must be placed at the end of the parameter
	function fn(a,b,...args){
    
    
    	console.log(a);
    	console.log(b);
    	console.log(args);
    }
    fn(1,2,3,4,5,6);

Note: rest parameters are very suitable for scenarios with variable number of parameter functions

2.8. spread spread operator

The spread operator (spread) is also three dots (…). It is like the inverse operation of the rest parameter, converting an array into a sequence of parameters separated by commas, and unpacking the array.

	//声明一个数组 ...
	const tfboys = ['德玛西亚之力','德玛西亚之翼','德玛西亚皇子'];
	// 声明一个函数
	function chunwan(){
    
    
    	console.log(arguments);
    }
    chunwan(...tfboys);// chunwan('易烊千玺','王源','王俊凯')

	//展开对象
	let skillOne = {
    
    
 		q: '致命打击',
	};
	let skillTwo = {
    
    
		w: '勇气'
	};
	let skillThree = {
    
    
 		e: '审判'
	};
	let skillFour = {
    
    
 		r: '德玛西亚正义'
	};
	let gailun = {
    
    ...skillOne, ...skillTwo,...skillThree,...skillFour};

2.9.Symbol

2.9.1. Basic usage of Symbol

ES6 introduces a new primitive data type Symbol, representing a unique value. It is the seventh data type of the JavaScript language and is a data type similar to strings.

  1. The value of Symbol is unique to resolve naming conflicts
	//创建Symbol
	let s = Symbol();
	// console.log(s, typeof s);
	let s2 = Symbol('张三');
    let s3 = Symbol('张三');
    //Symbol.for 创建
    let s4 = Symbol.for('李四');
    let s5 = Symbol.for('李四');
  1. Symbol values ​​cannot be manipulated with other data
	let result = s + 100; //报错
	let result = s > 100;
	let result = s + s;
  1. The Seven Data Types (Review)
	// USONB  you are so niubility 
	u  undefined
    s  string  
    s  symbol
    o  object
    n  null 
    n  number
    b  boolean

2.9.2. Symbol built-in values

In addition to defining the Symbol value used by itself, ES6 also provides 11 built-in Symbol values, which point to the methods used internally by the language. These methods can be called magic methods, because they will be executed automatically in certain scenarios.

method effect
Symbol.hasInstance This method is called when other objects use the instanceof operator to determine whether they are instances of the object
Symbol.isConcatSpreadable The Symbol.isConcatSpreadable property of the object is equal to a Boolean value, indicating whether the object can be expanded when used in Array.prototype.concat().
Symbol.species When creating derived objects, this property is used
Symbol.match When str.match(myObject) is executed, if the attribute exists, it will be called, returning the return value of the method.
Symbol.replace When the object is called by the str.replace(myObject) method, the return value of the method is returned.
Symbol.search When the object is called by the str.search(myObject) method, the method's return value is returned.
Symbol.split When the object is called by the str.split(myObject) method, the method's return value is returned.
Symbol.iterator When the object performs a for...of loop, the Symbol.iterator method will be called to return the default iterator of the object.
Symbol.toPrimitive When the object is converted to a primitive type value, this method will be called and the primitive type value corresponding to the object will be returned.
Symbol. toStringTag When the toString method is called on this object, return the return value of the method
Symbol. unscopables This object specifies which properties are excluded from the with environment when the with keyword is used.

2.10. Iterators

Iterator is one mechanism. It is an interface that provides a unified access mechanism for various data structures. Any data structure can complete the traversal operation as long as it deploys the Iterator interface.

  1. ES6 creates a new traversal command for…of loop, and the Iterator interface is mainly used for for…of consumption
	//声明一个数组
    const xiyou = ['唐僧','孙悟空','猪八戒','沙僧'];
    //使用 for...of 遍历数组
    for(let v of xiyou){
    
    
    	console.log(v);
    }
    let iterator = xiyou[Symbol.iterator]();
    //调用对象的next方法
    console.log(iterator.next());
    console.log(iterator.next());
    console.log(iterator.next());
    console.log(iterator.next());
    console.log(iterator.next());
  1. Native data with iterator interface (can be traversed with for of)

a) Array
b) Arguments
c) Set
d) Map
e) String
f) TypedArray
g) NodeList

  1. Working principle (iterator custom traversal data)

a) Create a pointer object to point to the starting position of the current data structure
b) Call the next method of the object for the first time, and the pointer will automatically point to the first member of the data structure
c) Next, call the next method continuously, and the pointer will move backwards , until pointing to the last member
d) Each call to the next method returns an object containing value and done attributes

	//声明一个对象
	const banji = {
    
    
            name: "终极一班",
            stus: [
                'xiaoming',
                'xiaoning',
                'xiaotian',
                'knight'
     ],
     [Symbol.iterator]() {
    
    
     	//索引变量
     	let index = 0;
     	//
     	let _this = this;
     	return {
    
    
     		next: function () {
    
    
     			if (index < _this.stus.length) {
    
    
     				const result = {
    
     value: _this.stus[index], done: false };
     				//下标自增
     				index++;
     				//返回结果
     				return result;
     			}else{
    
    
     				return {
    
    value: undefined, done: true};
     					}
     				}
     			};
     	   }
        }
        //遍历这个对象 
        for (let v of banji) {
    
    
            console.log(v);
        }

Note: When you need to customize the traversal data, think of iterators.

2.11. Generators

Generator functions are an asynchronous programming solution provided by ES6, and the syntax behavior is completely different from traditional functions.

  1. * The position is not limited
  2. The result returned by the generator function is an iterator object, and
    the value after the yield statement can be obtained by calling the next method of the iterator object
	//生成器其实就是一个特殊的函数
	//异步编程  纯回调函数  node fs  ajax mongodb
	//函数代码的分隔符
	function * gen(){
    
    
		// console.log(111);
		yield '一只没有耳朵';
		// console.log(222);
		yield '一只没有尾部';
		// console.log(333);
		yield '真奇怪';
		// console.log(444);
	}

	let iterator = gen();
    console.log(iterator.next());
    console.log(iterator.next());
    console.log(iterator.next());
    console.log(iterator.next());
    //遍历
    // for(let v of gen()){
    
    
    //     console.log(v);
    //
     }
  1. Yield is equivalent to the pause mark of the function, and can also be considered as the separator of the function. Every time the next
    method is called, a piece of code is executed
  2. The next method can pass actual parameters as the return value of the yield statement
	function * gen(arg){
    
    
		console.log(arg);
		let one = yield 111;
		console.log(one);
		let two = yield 222;
		console.log(two);
		let three = yield 333;
		console.log(three);
	}

	//执行获取迭代器对象
	let iterator = gen('AAA');
	console.log(iterator.next());
	//next方法可以传入实参
	console.log(iterator.next('BBB'));//第二个next传入的参数作为第一个yield的返回结果
	console.log(iterator.next('CCC'));//第三个next传入的参数作为第二个yield的返回结果
	console.log(iterator.next('DDD'));//第四个next传入的参数作为第三个yield的返回结果

generator function instance

	// 异步编程  文件操作 网络操作(ajax, request) 数据库操作
	// 1s 后控制台输出 111  2s后输出 222  3s后输出 333 
	// 回调地狱
		//setTimeout(() => {
    
    
			//console.log(111);
				//setTimeout(() => {
    
    
					//console.log(222);
						//setTimeout(() => {
    
    
							//console.log(333);
			//}, 3000);
		//}, 2000);
	//}, 1000);

	function one(){
    
    
		setTimeout(()=>{
    
    
			console.log(111);
			iterator.next();//回调
		},1000)
	}
	
	function two(){
    
    
		setTimeout(()=>{
    
    
			console.log(222);
			iterator.next();
		},1000)
	}
	
	function three(){
    
    
		setTimeout(()=>{
    
    
			console.log(333);
			iterator.next();//回调
		},1000)
	}
	
	function * gen(){
    
    
		yield one();
		yield two();
		yield three();//回调
	}

	//调用生成器函数
	let iterator = gen();
    iterator.next();

Generator function instance 2

		//模拟获取  用户数据  订单数据  商品数据 
        function getUsers(){
    
    
            setTimeout(()=>{
    
    
                let data = '用户数据';
                //调用 next 方法, 并且将数据传入
                iterator.next(data);
            }, 1000);
        }

        function getOrders(){
    
    
            setTimeout(()=>{
    
    
                let data = '订单数据';
                iterator.next(data);
            }, 1000)
        }

        function getGoods(){
    
    
            setTimeout(()=>{
    
    
                let data = '商品数据';
                iterator.next(data);
            }, 1000)
        }

        function * gen(){
    
    
            let users = yield getUsers();
            let orders = yield getOrders();
            let goods = yield getGoods();
        }

        //调用生成器函数
        let iterator = gen();
        iterator.next();

2.12. Promise

Promises are a new solution to asynchronous programming introduced by ES6. Syntactically Promise is a constructor that encapsulates an asynchronous operation and can obtain its success or failure result.

  1. basic use
//实例化 Promise 对象
        const p = new Promise(function(resolve, reject){
    
    	//实例化Promise对象要传入一个参数,参数为一个函数,该函数的参数是resolve和reject,分别代表正常和异常的状态 
            setTimeout(function(){
    
    
                //
                // let data = '数据库中的用户数据';
                // resolve
                // resolve(data);

                let err = '数据读取失败';
                reject(err);
            }, 1000);
        });

        //调用 promise 对象的 then 方法
        p.then(function(value){
    
    	//返回resolve调用这个函数
            console.log(value);
        }, function(reason){
    
      //返回reason调用这个函数
            console.error(reason);	
        })
  1. Promise package read file
//1. 引入 fs 模块
	const fs = require('fs');

//2. 调用方法读取文件
// fs.readFile('./resources/为学.md', (err, data)=>{
    
    
//     //如果失败, 则抛出错误
//     if(err) throw err;
//     //如果没有出错, 则输出内容
//     console.log(data.toString());
// });

//3. 使用 Promise 封装
	const p = new Promise(function(resolve, reject){
    
    
	    fs.readFile("./resources/为学.mda", (err, data)=>{
    
    
	        //判断如果失败
	        if(err) reject(err);
	        //如果成功
	        resolve(data);
	    });
	});
	
	p.then(function(value){
    
    
	    console.log(value.toString());
	}, function(reason){
    
    
	    console.log("读取失败!!");
	});
  1. Promise encapsulation AJAX
// 接口地址: https://api.apiopen.top/getJoke
        const p = new Promise((resolve, reject) => {
    
    
            //1. 创建对象
        const xhr = new XMLHttpRequest();

            //2. 初始化
            xhr.open("GET", "https://api.apiopen.top/getJ");

            //3. 发送
            xhr.send();

            //4. 绑定事件, 处理响应结果
            xhr.onreadystatechange = function () {
    
    
                //判断
                if (xhr.readyState === 4) {
    
    
                    //判断响应状态码 200-299
                    if (xhr.status >= 200 && xhr.status < 300) {
    
    
                        //表示成功
                        resolve(xhr.response);
                    } else {
    
    
                        //如果失败
                        reject(xhr.status);
                    }
                }
            }
        })
        
        //指定回调
        p.then(function(value){
    
    
            console.log(value);
        }, function(reason){
    
    
            console.error(reason);
        });
  1. Promise.prototype.then method
//创建 promise 对象
        const p = new Promise((resolve, reject)=>{
    
    
            setTimeout(()=>{
    
    
                resolve('用户数据');
                // reject('出错啦');
            }, 1000)
        });

        //调用 then 方法  then方法的返回结果是 Promise 对象, 对象状态由回调函数的执行结果决定
        //1. 如果回调函数中返回的结果是 非 promise 类型的属性, 状态为成功, 返回值为对象的成功的值
		//2. 如果回调函数中返回的结果是 promise 类型的属性, 返回值为该 promise 返回的状态
		//3. 如果回调函数中返回的结果是抛出错误, 返回状态是失败
        const result = p.then(value => {
    
    
             console.log(value);
            //1. 非 promise 类型的属性
            return 'iloveyou';
            //2. 是 promise 对象
            return new Promise((resolve, reject)=>{
    
    
                resolve('ok');
                //reject('error');
            });
            //3. 抛出错误
            throw new Error('出错啦!');
            throw '出错啦!';
        }, reason=>{
    
    
            console.warn(reason);
        });

        //链式调用
        p.then(value=>{
    
    

        }).then(value=>{
    
    

        });
  1. Promise to read multiple files
	//引入 fs 模块
	const fs = require("fs");
	
	// fs.readFile('./resources/为学.md', (err, data1)=>{
    
    
	//     fs.readFile('./resources/插秧诗.md', (err, data2)=>{
    
    
	//         fs.readFile('./resources/观书有感.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/为学.md", (err, data) => {
    
    
	        resolve(data);
	    });
	});
	
	p.then(value => {
    
    
	    return new Promise((resolve, reject) => {
    
    
	        fs.readFile("./resources/插秧诗.md", (err, data) => {
    
    
	            resolve([value, data]);
	        });
	    });
	}).then(value => {
    
    
	    return new Promise((resolve, reject) => {
    
    
	        fs.readFile("./resources/观书有感.md", (err, data) => {
    
    
	            //压入
	            value.push(data);
	            resolve(value);
	        });
	    })
	}).then(value => {
    
    
	    console.log(value.join('\r\n'));
	});
  1. The catch method of the Promise object
	const p = new Promise((resolve, reject)=>{
    
    
    setTimeout(()=>{
    
    
    	//设置 p 对象的状态为失败, 并设置失败的值
        reject("出错啦!");
        }, 1000)
     });

    // p.then(function(value){}, function(reason){
    
    
    //     console.error(reason);
    // });

    p.catch(function(reason){
    
    
    	console.warn(reason);
    });

2.13. Set

ES6 provides a new data structure Set (collection). It is similar to an array, but the values ​​of its members are all unique. The collection implements the iterator interface, so it can be traversed using the "extension operator" and "for...of...". The properties and methods of the collection:

  1. size returns the number of elements in the collection
  2. add adds a new element and returns the current collection
  3. delete deletes an element and returns a boolean value
  4. has checks whether the collection contains an element and returns a boolean value
  5. clear clears the collection and returns undefined
	//声明一个 set
    let s = new Set();
    let s2 = new Set(['大事儿','小事儿','好事儿','坏事儿','小事儿']);

    //元素个数
    console.log(s2.size);
    //添加新的元素
    s2.add('喜事儿');
    //删除元素
    s2.delete('坏事儿');
    //检测
    console.log(s2.has('糟心事'));
    //清空
    s2.clear();
    console.log(s2);

    for(let v of s2){
    
    
        console.log(v);
    }

collective practice

	let arr = [1,2,3,4,5,4,3,2,1];
	//1. 数组去重
	// let result = [...new Set(arr)];
	// console.log(result);
	//2. 交集
	let arr2 = [4,5,6,5,6];
	// let result = [...new Set(arr)].filter(item => {
    
    
	//     let s2 = new Set(arr2);// 4 5 6
	//     if(s2.has(item)){
    
    
	//         return true;
	//     }else{
    
    
	//         return false;
	//     }
	// });
	// let result = [...new Set(arr)].filter(item => new Set(arr2).has(item));
	// console.log(result);
	
	//3. 并集
	// let union = [...new Set([...arr, ...arr2])];
	// console.log(union);
	
	//4. 差集
	let diff = [...new Set(arr)].filter(item => !(new Set(arr2).has(item)));
	console.log(diff);

2.14. Map

ES6 provides the Map data structure. It is similar to an object and is also a collection of key-value pairs. But the scope of "key" is not limited to strings, and various types of values ​​(including objects) can be used as keys. Map also implements the iterator interface, so it can be traversed using "spread operator" and "for...of...". Properties and methods of Map:

  1. size returns the number of elements in the Map
  2. set adds a new element and returns the current Map
  3. get returns the key value of the key object
  4. has detects whether an element is contained in the Map and returns a boolean value
  5. clear clears the collection and returns undefined
	//声明 Map
	let m = new Map();
	
	//添加元素
	m.set('name','上官');
	m.set('change', function(){
    
    
	    console.log("我们可以改变你!!");
	});
	let key = {
    
    
	    school : 'ATGUIGU'
	};
	m.set(key, ['北京','上海','深圳']);
	
	//size
	// console.log(m.size);
	
	//删除
	// m.delete('name');
	
	//获取
	// console.log(m.get('change'));
	// console.log(m.get(key));
	
	//清空
	// m.clear();
	
	//遍历
	for(let v of m){
    
    
	    console.log(v);
	}
	
	// console.log(m);

2.15. class class

  ES6 provides a way of writing closer to traditional languages, introducing the concept of Class (class) as an object
template. With the class keyword, a class can be defined. Basically, the ES6 class can be regarded as just
a syntactic sugar. Most of its functions can be achieved by ES5. The new class writing method only makes the object
prototype writing method clearer and more like the syntax of object-oriented programming.

ES5 defines class-related operations:

	//手机
	function Phone(brand, price){
    
    
	    this.brand = brand;
	    this.price = price;
	}
	
	//添加方法
	Phone.prototype.call = function(){
    
    
	    console.log("我可以打电话!!");
	}
	
	//实例化对象
	let Huawei = new Phone('华为', 5999);
	Huawei.call();
	console.log(Huawei);

ES6 defines class-related operations:

  1. class declares the class
  2. constructor defines constructor initialization
//class
	class Shouji{
    
    
	    //构造方法 名字不能修改
	    constructor(brand, price){
    
    
	        this.brand = brand;
	        this.price = price;
	    }
	   //方法必须使用该语法, 不能使用 ES5 的对象完整形式
		call(){
    
    
		       console.log("我可以打电话!!");
		   }
		}
		
		let onePlus = new Shouji("1+", 1999);
		
		console.log(onePlus); 
  1. extends inherits the parent class (ES6)
  2. super calls the parent constructor
    ES5 syntax:
	//手机
	function Phone(brand, price){
    
    
	   this.brand = brand;
	   this.price = price;
	}
	
	Phone.prototype.call = function(){
    
    
	   console.log("我可以打电话");
	}
	
	//智能手机
	function SmartPhone(brand, price, color, size){
    
    
	   Phone.call(this, brand, price);
	   this.color = color;
	   this.size = size;
	}
	
	//设置子级构造函数的原型
	SmartPhone.prototype = new Phone;
	SmartPhone.prototype.constructor = SmartPhone;
	
	//声明子类的方法
	SmartPhone.prototype.photo = function(){
    
    
	   console.log("我可以拍照")
	}
	
	SmartPhone.prototype.playGame = function(){
    
    
	   console.log("我可以玩游戏");
	}
	
	const chuizi = new SmartPhone('锤子',2499,'黑色','5.5inch');
	
	console.log(chuizi);

ES6 syntax:

	class Phone{
    
    
	    //构造方法
	    constructor(brand, price){
    
    
	        this.brand = brand;
	        this.price = price;
	    }
	    //父类的成员属性
	    call(){
    
    
	        console.log("我可以打电话!!");
	    }
	}
	
	class SmartPhone extends Phone {
    
    
	    //构造方法
	    constructor(brand, price, color, size){
    
    
	        super(brand, price);// Phone.call(this, brand, price)
	        this.color = color;
	        this.size = size;
	    }
	
	    photo(){
    
    
	        console.log("拍照");
	    }
	
	    playGame(){
    
    
	        console.log("玩游戏");
	    }
	
	    call(){
    
    
	        console.log('我可以进行视频通话');
	    }
	}
	
	const xiaomi = new SmartPhone('小米',799,'黑色','4.7inch');
	// console.log(xiaomi);
	xiaomi.call();
	xiaomi.photo();
	xiaomi.playGame();
  1. static defines static methods and properties
	class Phone{
    
    
	    //静态属性
	    static name = '手机';
	    static change(){
    
    
	        console.log("我可以改变世界");
	    }
	}
	
	let nokia = new Phone();
	console.log(nokia.name);	//不可访问
	console.log(Phone.name);	//可访问
  1. Parent class methods can be overridden
	//父类
	class Phone {
    
    
	 //构造方法
	 constructor(brand, color, price) {
    
    
	 this.brand = brand;
	 this.color = color;
	 this.price = price;
	 }
	 //对象方法
	 call() {
    
    
	 console.log('我可以打电话!!!')
	 } }
	//子类
	class SmartPhone extends Phone {
    
    
	 constructor(brand, color, price, screen, pixel) {
    
    
	 super(brand, color, price);
	 this.screen = screen;
	 this.pixel = pixel;
	 }
	 //子类方法
	 photo(){
    
    
	 console.log('我可以拍照!!');
	 }
	 playGame(){
    
    
	 console.log('我可以玩游戏!!');
	 }
	 //方法重写
	 call(){
    
    
	 console.log('我可以进行视频通话!!');
	 }
	 //静态方法
	 static run(){
    
    
	 console.log('我可以运行程序')
	 }
	 static connect(){
    
    
	 console.log('我可以建立连接')
	 } }
	//实例化对象
	const Nokia = new Phone('诺基亚', '灰色', 230);
	const iPhone6s = new SmartPhone('苹果', '白色', 6088, '4.7inch','500w');
	//调用子类方法
	iPhone6s.playGame();
	//调用重写方法
	iPhone6s.call();
	//调用静态方法
	SmartPhone.run();

2.16. Numeric Expansion

2.16.1. Binary and Octal

ES6 provides a new way of writing binary and octal values, which are represented by prefixes 0b and 0o respectively.

	 //二进制和八进制
	 let b = 0b1010;
	 let o = 0o777;
	 let d = 100;
	 let x = 0xff;
	 console.log(x);	//255

2.16.2. Number.isFinite() 与 Number.isNaN()

Number.isFinite() is used to check whether a value is finite
Number.isNaN() is used to check whether a value is NaN

	//Number.isFinite  检测一个数值是否为有限数
	console.log(Number.isFinite(100));
	console.log(Number.isFinite(100/0));
	console.log(Number.isFinite(Infinity));
	
	//Number.isNaN 检测一个数值是否为 NaN 
	console.log(Number.isNaN(123)); 

2.16.3. Number.parseInt() and Number.parseFloat()

ES6 transplants the global methods parseInt and parseFloat to the Number object, and uses them unchanged.

	//Number.parseInt Number.parseFloat字符串转整数
	console.log(Number.parseInt('5211314love'));
	console.log(Number.parseFloat('3.1415926神奇'));

2.16.4. Math.trunc

Used to remove the fractional part of a number and return the integer part.

	//Math.trunc 将数字的小数部分抹掉  
	console.log(Math.trunc(3.5));

2.16.5. Number.isInteger

Number.isInteger() is used to determine whether a value is an integer

	//5. Number.isInteger 判断一个数是否为整数
	console.log(Number.isInteger(5));
	console.log(Number.isInteger(2.5));

2.16.6. Math.sign

	//Math.sign 判断一个数到底为正数 负数 还是零
	console.log(Math.sign(100));
	console.log(Math.sign(0));
	console.log(Math.sign(-20000));

2.17. Object Extensions

2.17.1. Object.is

	//Object.is 判断两个值是否完全相等 
	console.log(Object.is(120, 120));// === 
	console.log(Object.is(NaN, NaN));// === 
	console.log(NaN === NaN);// === 

2.17.2. Object.assign

	//Object.assign 对象的合并
	const config1 = {
    
    
	    host: 'localhost',
	    port: 3306,
	    name: 'root',
	    pass: 'root',
	    test: 'test'
	};
	const config2 = {
    
    
	    host: 'http://atguigu.com',
	    port: 33060,
	    name: 'atguigu.com',
	    pass: 'iloveyou',
	    test2: 'test2'
	}
	console.log(Object.assign(config1, config2));	//出现重名,后面参数属性覆盖前面

2.17.3. Object.setPrototypeOf

	//Object.setPrototypeOf 设置原型对象
	const school = {
    
    
	    name: '上官'
	}
	const cities = {
    
    
	    xiaoqu: ['北京','上海','深圳']
	}
	Object.setPrototypeOf(school, cities);
	console.log(Object.getPrototypeOf(school));
	console.log(school);

2.18. Modularity

  Modularization refers to splitting a large program file into many small files, and then combining the small files.

2.18.1. Benefits of Modularity

The advantages of modularity are as follows:

  1. prevent naming conflicts
  2. code reuse
  3. high maintenance

2.18.2. Modular Specification Products

Modular specifications prior to ES6 are:

  1. CommonJS => NodeJS、Browserify
  2. AMD => requireJS
  3. CMD => seaJS

2.18.3. ES6 modular syntax

The module function mainly consists of two commands: export and import.

⚫ The export command is used to specify the external interface of the module
⚫ The import command is used to import the functions provided by other modules

The following are three independent js files:

1. Separate exposure

	//分别暴露
	export let school = '上官';
	
	export function teach() {
    
    
	    console.log("我们可以教给你开发技能");
	}

2. Uniform Exposure

	//统一暴露
	let school = '上官';
	
	function findJob(){
    
    
	    console.log("我们可以帮助你找工作!!");
	}
	
	//
	export {
    
    school, findJob};

3. Default exposure

	//默认暴露
	export default {
    
    
	    school: 'ATSHANGGUAN',
	    change: function(){
    
    
	        console.log("我们可以改变你!!");
	    }
	}

The following is the import method of the html module: (After importing, you can directly use the relevant elements in the module)

<script type="module">
        //1. 通用的导入方式
       // 引入 m1.js 模块内容
        import * as m1 from "./src/js/m1.js";//模块相对路径
        //引入 m2.js 模块内容
        import * as m2 from "./src/js/m2.js";
        //引入 m3.js 
        import * as m3 from "./src/js/m3.js";

        //2. 解构赋值形式
        import {
    
    school, teach} from "./src/js/m1.js";
        import {
    
    school as shangguan, findJob} from "./src/js/m2.js";//as重命名
        import {
    
    default as m3} from "./src/js/m3.js";

        //3. 简便形式  针对默认暴露
        import m3 from "./src/js/m3.js";
        console.log(m3);
</script>
<script src="./src/js/app.js" type="module"></script>

The above is the way to import modules separately. The following will introduce the introduction of NPM packages for import. This time, the three files packaged separately above are packaged:

	//入口文件
	
	//模块引入
	import * as m1 from "./m1.js";
	import * as m2 from "./m2.js";
	import * as m3 from "./m3.js";
	
	console.log(m1);
	console.log(m2);
	console.log(m3);
	
	m1.teach();
	m2.findJob();
	m3.default.change();
	
	//修改背景颜色为粉色
	import $ from 'jquery';// const $ = require("jquery");
	$('body').css('background','pink');

Preparations before introducing html:

  1. Install tools npm i babel-cli babel-preset-env browserify(webpack) -D
  2. Compile npx babel src/js -d dist/js --presets=babel-preset-env (babel performs format conversion)
  3. package npx browserify dist/js/app.js -o dist/bundle.js

After some operations, it will be generated in this directorydist/bundle.jsfile, introduced in html:

	<script src="dist/bundle.js"></script>

All elements in the package are ready to use.



Chapter 3 ECMASript 7 New Features

3.1.Array.prototype.includes

The Includes method is used to detect whether an element is contained in the array and returns a Boolean value

	// includes   indexOf
	// const mingzhu = ['西游记','红楼梦','三国演义','水浒传'];
	
	//判断
	console.log(mingzhu.includes('西游记'));
	console.log(mingzhu.includes('金瓶梅'));
	
	

3.2. Exponent operator

	// **
	console.log(2 ** 10);	//2的10次方
	console.log(Math.pow(2, 10));	



Chapter 4 ECMASript 8 New Features

4.1. async and await

The combination of async and await can make asynchronous code look like synchronous code

4.1.1. async functions

  1. The return value of the async function is a promise object
  2. The result of the promise object is determined by the return value of the async function execution
	//async 函数
	async function fn(){
    
    
	    // 返回一个字符串
	    // return '上官';
	    // 返回的结果不是一个 Promise 类型的对象, 返回的结果就是成功 Promise 对象
	    // return;
	    //抛出错误, 返回的结果是一个失败的 Promise
	    // throw new Error('出错啦!');
	    //返回的结果如果是一个 Promise 对象
	    return new Promise((resolve, reject)=>{
    
    
	        resolve('成功的数据');
	        // reject("失败的错误");
	    });
	}
	
	const result = fn();
	
	//调用 then 方法
	result.then(value => {
    
    
	    console.log(value);
	}, reason => {
    
    
	    console.warn(reason);
	})

4.1.2. await expressions

  1. await must be written in an async function
  2. The expression on the right side of await is generally a promise object
  3. await returns the value of promise success
  4. If the promise of await fails, an exception will be thrown, which needs to be captured and processed by try...catch
	//创建 promise 对象
	const p = new Promise((resolve, reject) => {
    
    
	    // resolve("用户数据");
	    reject("失败啦!");
	})
	
	// await 要放在 async 函数中.
	async function main() {
    
    
	    try {
    
    
	        let result = await p;
	        //
	        console.log(result);
	    } catch (e) {
    
    
	        console.log(e);
	    }
	}
	//调用函数
	main();

4.1.3. -async and await combined to read files

	//1. 引入 fs 模块
	const fs = require("fs");
	
	//读取『为学』
	function readWeiXue() {
    
    
	    return new Promise((resolve, reject) => {
    
    
	        fs.readFile("./resources/为学.md", (err, data) => {
    
    
	            //如果失败
	            if (err) reject(err);
	            //如果成功
	            resolve(data);
	        })
	    })
	}
	
	function readChaYangShi() {
    
    
	    return new Promise((resolve, reject) => {
    
    
	        fs.readFile("./resources/插秧诗.md", (err, data) => {
    
    
	            //如果失败
	            if (err) reject(err);
	            //如果成功
	            resolve(data);
	        })
	    })
	}
	
	function readGuanShu() {
    
    
	    return new Promise((resolve, reject) => {
    
    
	        fs.readFile("./resources/观书有感.md", (err, data) => {
    
    
	            //如果失败
	            if (err) reject(err);
	            //如果成功
	            resolve(data);
	        })
	    })
	}
	
	//声明一个 async 函数
	async function main(){
    
    
	    //获取为学内容
	    let weixue = await readWeiXue();
	    //获取插秧诗内容
	    let chayang = await readChaYangShi();
	    // 获取观书有感
	    let guanshu = await readGuanShu();
	
	    console.log(weixue.toString());
	    console.log(chayang.toString());
	    console.log(guanshu.toString());
	}
	
	main();

4.1.4. async and await encapsulate AJAX requests

	// 发送 AJAX 请求, 返回的结果是 Promise 对象
	function sendAJAX(url) {
    
    
	    return new Promise((resolve, reject) => {
    
    
	        //1. 创建对象
	        const x = new XMLHttpRequest();
	
	        //2. 初始化
	        x.open('GET', url);
	
	        //3. 发送
	        x.send();
	
	        //4. 事件绑定
	        x.onreadystatechange = function () {
    
    
	            if (x.readyState === 4) {
    
    
	                if (x.status >= 200 && x.status < 300) {
    
    
	                    //成功啦
	                    resolve(x.response);
	                }else{
    
    
	                    //如果失败
	                    reject(x.status);
	                }
	            }
	        }
	    })
	}
	
	//promise then 方法测试
	// sendAJAX("https://api.apiopen.top/getJoke").then(value=>{
    
    
	//     console.log(value);
	// }, reason=>{})
	
	// async 与 await 测试  axios
	async function main(){
    
    
	    //发送 AJAX 请求
	    let result = await sendAJAX("https://api.apiopen.top/getJoke");
	    //再次测试
	    let tianqi = await sendAJAX('https://www.tianqiapi.com/api/?version=v1&city=%E5%8C%97%E4%BA%AC&appid=23941491&appsecret=TXoD5e8P')
	
	    console.log(tianqi);
	}
	
	main();

4.2.Object.values 和 Object.entries

  1. The Object.values() method returns an array of all enumerable property values ​​for a given object
  2. The Object.entries() method returns an array of traversable properties [key, value] for a given object itself
//声明对象
	const school = {
    
    
	    name:"尚硅谷",
	    cities:['北京','上海','深圳'],
	    xueke: ['前端','Java','大数据','运维']
	};
	
	//获取对象所有的键
	console.log(Object.keys(school));
	//获取对象所有的值
	console.log(Object.values(school));
	//entries
	console.log(Object.entries(school));
	//创建 Map
	const m = new Map(Object.entries(school));
	console.log(m.get('cities'));
	
	//对象属性的描述对象
	console.log(Object.getOwnPropertyDescriptors(school));
	
	const obj = Object.create(null, {
    
    
	    	name: {
    
    
	       //设置值
	        value: '尚硅谷',
	        //属性特性
	        writable: true,
	        configurable: true,
	        enumerable: true
	   } 
	 });

Chapter 5 New Features in ECMASript 9

5.1. Rest/Spread properties

Rest parameters and spread extension operators have been introduced in ES6, but ES6 is only for arrays, and ES9 provides array-like rest parameters and extension operators for objects

	function connect({
     
     host, port, ...user}) {
    
    
	 console.log(host);
	 console.log(port);
	 console.log(user);
	}
	connect({
    
    
	 host: '127.0.0.1',
	 port: 3306,
	 username: 'root',
	 password: 'root',
	 type: 'master'
	});

5.2. Regular expression named capture group

ES9 allows named capture groups to use the symbol "?", so that the capture results are more readable

	let str = '<a href="http://www.shangguan.com">上官</a>';
	const reg = /<a href="(?<url>.*)">(?<text>.*)<\/a>/;
	const result = reg.exec(str);
	console.log(result.groups.url);
	console.log(result.groups.text);

5.3. Regular expression reverse assertion

ES9 supports reverse assertion, which filters the match by judging the content in front of the matching result.

	//声明字符串
	let str = 'JS5211314 你知道么 555 啦啦啦';
	//正向断言
	const reg = /\d+(?=啦)/;
	const result = reg.exec(str);
	//反向断言
	const reg = /(?<=么)\d+/;
	const result = reg.exec(str);
	console.log(result);

5.4. Regular expression dotAll mode

Midpoint in the regular expression. Match any single character except the carriage return. The mark "s" changes this behavior and allows line terminators to appear

	let str = `
	<ul>
	 <li>
	 <a>肖生克的救赎</a>
	 <p>上映日期: 1994-09-10</p>
	 </li>
	 <li>
	 <a>阿甘正传</a>
	 <p>上映日期: 1994-07-06</p>
	 </li>
	</ul>`;
	//声明正则
	const reg = /<li>.*?<a>(.*?)<\/a>.*?<p>(.*?)<\/p>/gs;
	//执行匹配
	const result = reg.exec(str);
	let result;
	let data = [];
	while(result = reg.exec(str)){
    
    
	 data.push({
    
    title: result[1], time: result[2]});
	}
	//输出结果
	console.log(data);

Chapter 6 ECMASript 10 New Features

6.1.Object.fromEntries

The Object.fromEntries method is used to create an object, and the received parameter is a two-dimensional array or Map

	const result = Object.fromEntries([
	    ['name','黑马'],
	    ['xueke', 'Java,大数据,前端,云计算']
	]);
	console.log(result);
	const m = new Map();
	m.set('name','ATGUIGU');
	const result1 = Object.fromEntries(m);
	console.log(result1);
	const arr = Object.entries({
    
    
	   name: "尚硅谷"
	})
	console.log(arr);

6.2. trimStart and trimEnd

The trimStart method is used to delete the spaces before the string, trimEnd is used to delete the spaces after the string

	let str = '   iloveyou   ';
	
	console.log(str);
	console.log(str.trimStart());
	console.log(str.trimEnd());

6.3.Array.prototype.flat 与 flatMap

The Array.prototype.flat method is used to reduce the dimensionality of a two-dimensional array and convert it into a one-dimensional array. The parameter of the method can be depth, which can control the depth of dimensionality reduction. The flatMap method can not only reduce dimensionality, but also process the operated object return

	//flat 平
	//将多维数组转化为低位数组
	const arr = [1,2,3,4,[5,6]];
	const arr = [1,2,3,4,[5,6,[7,8,9]]];
	//参数为深度 是一个数字
	console.log(arr.flat(2));  
	
	//flatMap
	const arr = [1,2,3,4];
	const result = arr.flatMap(item => [item * 10]);
	console.log(result);

6.4.Symbol.prototype.description

Symbol.prototype.description method is used to get the string description of Symbol

	//创建 Symbol
	let s = Symbol('尚硅谷');
	
	console.log(s.description);

Chapter 7 ECMASript 11 New Features

7.1.Promise.allSettled

The Promise.allSettled method receives a Promise array and returns a Promise object, and the returned status is always successful

	//声明两个promise对象
	const p1 = new Promise((resolve, reject)=>{
    
    
	    setTimeout(()=>{
    
    
	        resolve('商品数据 - 1');
	    },1000)
	});
	
	const p2 = new Promise((resolve, reject)=>{
    
    
	    setTimeout(()=>{
    
    
	        resolve('商品数据 - 2');
	        // reject('出错啦!');
	    },1000)
	});
	
	//调用 allsettled 方法
	const result = Promise.allSettled([p1, p2]);
	const res = Promise.all([p1, p2]);
	console.log(res);

7.2. Class private properties

Similar to Java, it cannot be directly accessed outside the class, but can only be accessed through method internal encapsulation calls

	class Person{
    
    
	//公有属性
	name;
	//私有属性
	#age;
	#weight;
	//构造方法
	constructor(name, age, weight){
    
    
	    this.name = name;
	    this.#age = age;
	    this.#weight = weight;
	}
	
	intro(){
    
    
	    console.log(this.name);
	    console.log(this.#age);
	    console.log(this.#weight);
	}
	}
	
	//实例化
	const girl = new Person('晓红', 18, '45kg');
	
	// console.log(girl.name);
	// console.log(girl.#age);
	// console.log(girl.#weight);
	
	girl.intro();

7.3.String.prototype.matchAll

The String.prototype.matchAll method is used to obtain regular batch matching results, which can match the matching objects and matching results in an array

	let str = `<ul>
	    <li>
	        <a>肖生克的救赎</a>
	        <p>上映日期: 1994-09-10</p>
	    </li>
	    <li>
	        <a>阿甘正传</a>
	        <p>上映日期: 1994-07-06</p>
	    </li>
	</ul>`;
	
	//声明正则
	const reg = /<li>.*?<a>(.*?)<\/a>.*?<p>(.*?)<\/p>/sg
	
	//调用方法
	const result = str.matchAll(reg);
	
	// for(let v of result){
    
    
	//     console.log(v);
	// }
	
	const arr = [...result];//返回匹配结果为可迭代对象,既可以用for...of遍历,也可以用扩展运算符进行展开
	
	console.log(arr);

7.4. Optional Chaining Operators

This is a judgment process that can obtain object attributes in provinces, regions and multi-levels

	// ?.
	function main(config){
    
    
	    // const dbHost = config && config.db && config.db.host;
	    const dbHost = config?.db?.host;
	
	    console.log(dbHost);
	}
	
	main({
    
    
	    db: {
    
    
	        host:'192.168.1.100',
	        username: 'root'
	    },
	    cache: {
    
    
	        host: '192.168.1.200',
	        username:'admin'
	    }
	})

7.5. Dynamic import import

	export function hello(){
    
    
	    alert('Hello');
	}
	// import * as m1 from "./hello.js";
	//获取元素
	const btn = document.getElementById('btn');
	
	btn.onclick = function(){
    
    
	    import('./hello.js').then(module => {
    
    
	        module.hello();
	    });
	}

7.6. globalThis object

globalThis points to the global object and can operate on the global object

console.log(globalThis);	//global(node.js)或者window(html)

7.7.BigInt

	//大整形
	// let n = 521n;
	// console.log(n, typeof(n));   //bigint类型
	
	//函数
	let n = 123;
	console.log(BigInt(n));
	console.log(BigInt(1.2));//报错
	
	//大数值运算
	let max = Number.MAX_SAFE_INTEGER;  //最大安全整数
	console.log(max);
	console.log(max + 1);   
	console.log(max + 2);   //不变,已经很大了
	
	console.log(BigInt(max))
	console.log(BigInt(max) + BigInt(1))
	console.log(BigInt(max) + BigInt(2))    //变化

Guess you like

Origin blog.csdn.net/qq_62361050/article/details/127327550