Front-end learning ES6-ES11

ES6

let

1. Variables cannot be declared repeatedly

Variable names declared by let cannot be repeated to avoid variable contamination.

let star = '罗志祥';
let star = '小猪';
console.log(star);

Insert image description here
Variables declared with var can be repeated, and subsequent values ​​will overwrite previous values.

var star = '罗志祥';
var star = '小猪';
console.log(star);

Insert image description here

2. Block-level scope

If you declare a variable using let in block scope, you have block scope

{
    
    
	let myName= '王思聪';
}
console.log(myName);

Insert image description here
Use var to declare variables in block-level scope, without block-level scope

{
    
    
	var myName= '王思聪';
}
console.log(myName);

Insert image description here

3. There is no variable promotion

Before let declares the variable, if the variable is printed first, an error will be reported and there will be no variable promotion.

console.log(song);
let song = '日不落';

Insert image description here
Before var declares a variable, if you print the variable first, undefined will be printed. Because the variable declared by var has variable promotion, the variable will be declared at the beginning, and then the assignment will start at " var song = '日不落';", so no error will be reported.

console.log(song);
var song = '日不落';

Insert image description here

4. Does not affect the scope chain

When a variable cannot be found in the block-level scope, go back to the global scope to find it. Variables declared by let do not affect the scope chain.

let myAge = 18;
{
    
    
	console.log(myAge );
}

Insert image description here

5. Classic examples of let

Purpose: Click on the div, and the div will turn pink, as shown in the picture:
Insert image description here

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<style>
			.cantainer {
      
      
				display: flex;
			}
			
			.item {
      
      
				margin: 10px;
				width: 100px;
				height: 60px;
				border: solid black 1px;
			}
		</style>
		<script type="text/javascript">
			window.onload = function() {
      
      
				// 获取div元素对象
				let items = document.getElementsByClassName('item');

				//遍历并绑定事件
				for(var i = 0; i < items.length; i++) {
      
      
					items[i].onclick = function() {
      
      
						//this.style.background = 'pink';//可以使用
						
						//不能使用,因为 var 声明的变量没有块级作用域的说法,后面 i 会变成 3,但是没有下标为 3的元素,故报错。
						items[i].style.background = 'pink';
					}
				}
			}
		</script>
	</head>

	<body>
		<div class='cantainer'>
			<div class='item'></div>
			<div class='item'></div>
			<div class='item'></div>
		</div>
	</body>

</html>

Insert image description here
Here, var is used to declare variable i. Because there is no block-level scope, i will become 3, but there is no element with subscript 3, so an error is reported. But use let to declare variable i, because there is block-level scope, no error will be reported, and it can run successfully.

const

1.const is used to declare constants (amount whose value cannot be modified is called a constant)

const SCHOOL = '河池学院';
console.log(SCHOOL); // 常量一般使用大写(潜规则)

2. Constants must be assigned initial values.

const A;

Insert image description here

3. The value of a constant cannot be modified.

const SCHOOL = '河池学院';
SCHOOL = 'hcuniversity';
console.log(SCHOOL); // 常量一般使用大写(潜规则)

Insert image description here

4. Block-level scope

{
    
    
	const PLAYER = 'UZI';
}
console.log(PLAYER); // 常量一般使用大写(潜规则)

Insert image description here

5. Modification of elements of arrays and objects does not count as modification of constants, and no error will be reported.

const ARRAY = ['A','B','C','D'];
ARRAY.push('E');
console.log(ARRAY); 

Insert image description hereBecause the reference to the constant address has not been changed, it is not considered a modification, and the same is true for the object.

Destructuring assignment

ES6 allows you to extract values ​​from arrays and objects according to certain patterns and assign values ​​to variables. This is called destructuring assignment.

  1. Array destructuring
const F4 =['小沈阳','刘能','赵四','宋小宝'];
let [xiao, liu, zhao, song]= F4; // 将F4数组的值赋值给[xiao, liu, zhao, song]
console.log(xiao);
console.log(liu);
console.log(zhao);
console.log(song);

Insert image description here

  1. Deconstruction of objects
const player = {
    
    
	name: 'UZI',
	gender: '男',
	operate: function() {
    
    
		console.log('我要拿五杀!');
	}
}
let {
    
    name, gender, operate, age} = player; // 将对象player中的值依次赋给{name, gender, operate, age}
console.log(name);
console.log(gender);
console.log(operate);
console.log(age);  // 因为player中只有三个值,故age的值为undefined
operate(); // 直接调用方法,不需要用player.operate()的方式来调用,可以省略player

Insert image description here

Template string (backtick)

1. Statement

let str = `我也是字符串!`;
console.log(str, typeof str);

Insert image description here

2. You can use line breaks directly

let ul = `<ul>
		   	<li>沈腾</li>
			<li>玛丽</li>
			<li>魏翔</li>
			<li>艾伦</li>
		</ul>`; // 单引号和双引号都不能这样赋值,反引号却可以。

3. Variable splicing

let lovest ='沈腾';
let out =`${
      
       lovest }是我心目中最搞笑的演员!!`;
console.log(out);

Insert image description here

Simplify object writing

let name = '孙悟空';
let age = 18;
let operate = function() {
    
    
	console.log('我会七十二变!');
}
 
 const person ={
    
    
	name, // 简化写法,相当于name:name
	age,
	operate,
	say(){
    
     // 简化写法,省略function
		console.log('妖怪,哪里跑!');
	}
} 
console.log(person);

Insert image description here

arrow function

1. Statement

let fun = (a, b) => {
    
     // 省略了function,加入了=>
	return a+b;
}
let result= fun(1,2);
console.log(result); // 3

2.this is static. this always points to the value of this in the scope where the function is declared.

let fun1 = function() {
    
    
	console.log(this.name);
}
let fun2 = () => {
    
    
	console.log(this.name);
}
window.name = '孙悟空';
const myName = {
    
    
	name:'猪八戒'
}

// 1. 直接调用
fun1();  // 指向 window
fun2();  // 指向 window
// 2. 使用call方法调用
fun1.call(myName);  // 用call改变指向对象,指向 myName
fun2.call(myName);  // 没有改变指向对象,还是指向 window

Insert image description here

3. Objects cannot be instantiated as constructors

let Person = (name, age) => {
    
    
this.name = name;
this.age = age;
}
let me = new Person('孙悟空',18);
console.log(me);

Insert image description here
Error: Person is not a constructor

4. Arguments variables cannot be used

let fun = function() {
    
    
console.log(arguments);
}
fun(1,2,3);

Insert image description here

let fun1 = () => {
    
    
console.log(arguments);
}
fun1(1,2,3);

Insert image description here

5. Abbreviation for arrow function

  1. When there is only one parameter, you can omit ()
let add = n => {
    
     // 省略小括号()
	return n+n;
}
console.log(add(10)); // 20
  1. When the function code body has only one sentence, {} can be omitted, and return can be omitted. The execution result of the statement will be returned as the return value.
let pow = n =>  n*n; // 省略(),{}和return
console.log(add(10)); // 100

Arrow functions are suitable for callbacks that have nothing to do with this. For example: timers, array method callbacks, etc.
Arrow functions are not suitable for callbacks related to this. Such as: event callbacks, object methods, etc.

rest parameters and spread operators

Here I see a blog post by a master. Is it detailed? I recommend it to everyone on
the ES6 learning path 3----rest parameters and expansion operators.

Symbol type

1.What is Symbol type?

Symbol is a basic data type in ES6. The Symbol() function returns a value of type Symbol, which has static methods and static properties.

2. Why use Symbol type?

ES5 object property names are all strings, which can easily cause property name conflicts.

For example, if you use an object provided by others but want to add a new method to the object, the name of the new method may conflict with the existing method.

It would be great if there was a mechanism to ensure that the name of each attribute is unique, thus fundamentally preventing attribute name conflicts. This is why ES6 introduced the Symbol type.

3. How to use Symbol type

More details here

Getting Started with ECMAScript 6

ES7

1.Array.prototype.includes

The Includes method is used to detect whether an array contains an element and returns a Boolean value.

const array = ['孙悟空', '猪八戒', '沙和尚', '唐三藏'];
console.log(array.includes('孙悟空')); // true
console.log(array.includes('白骨精')); // false

2. Exponential operator

The exponent operator "**" is introduced in ES7 to implement exponentiation. The function is the same as the Math.pow result.

console.log(2 ** 10); // 1024
console.log(Math.pow(2, 10)); // 1024

ES8

1.async function

  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 function fun() {
    
    
	return 1;
}
let result = fun();
console.log(result);

Insert image description here
A promise object whose result is a success state

async function fun() {
    
    
	throw error // 抛出错误
}
let result = fun();
console.log(result);

Insert image description here
A promise object whose result is a failed state

2.await expression

  1. await must be written in async function
  2. The expression on the right side of await is generally a promise object
  3. await returns the successful value of promise
  4. If the promise of await fails, an exception will be thrown, which needs to be caught and processed through try...catch
async function fun() {
    
    
	try {
    
    
		let success= await Promise.resolve('我成功了');
		console.log(success);
		// await Promise.reject('我失败了');
	} catch(error) {
    
    
		console.log(error)
	}
}
fun();

3.Object.values 、Object.entries 和 Object.getOwnPropertyDescriptors

  1. The Object.values() method returns an array of all enumerable property values ​​of a given object.
  2. The Object.entries() method returns an array of the traversable properties [key, value] of the given object itself.
const book = {
    
    
	name:'西游记',
	person:['孙悟空', '猪八戒','沙和尚', '唐三藏'],
	event:['三打白骨精', '智取芭蕉扇', '大闹天宫']
}
// 获取对象所有的键
console.log(Object.keys(book));
// 获取对象所有的值
console.log(Object.values(book));
// 获取对象所有的键值对
console.log(Object.entries(book));
// 获取有属性描述的对象
console.log(Object.getOwnPropertyDescriptors(book));

Insert image description here

ES9

1.Rest/Spread attribute

Rest parameters and spread operators have been introduced in ES6, but ES6 only applies to arrays. In
ES9, rest parameters and spread operators like arrays are provided 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'
});

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.baidu.com">百度</a>';
const reg = /<a href="(?<url>.*)">(?<text>.*)<\/a>/;
const result = reg.exec(str);
console.log(result.groups.url); // http://www.baidu.com
console.log(result.groups.text); // 百度

3. Regular expression dotAll pattern

Regular expression midpoint. Matches any single character except carriage return. The flag '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;
//执行匹配
let data = [];
while(result = reg.exec(str)){
    
    
	data.push({
    
    title: result[1], time: result[2]});
}
//输出结果
console.log(data);

Insert image description here

ES10

Object.fromEntries 和 Object.entries

Object.fromEntries converts a two-dimensional array into an object

const result = Object.fromEntries([
    ['name', '孙悟空'],
    ['event', '大闹天宫']
])
console.log(result);

Insert image description here

Object.entries converts objects into two-dimensional arrays

const result1 = Object.entries({
    
    
    name:'孙悟空'
})
console.log(result1);

Insert image description here

trimStart and trimEnd

const str = '   123   ';
console.log(str);
console.log(str.trim()); // 去除左右两边的空格
console.log(str.trimStart()); // 去除左边的空格
console.log(str.trimEnd()); // 去除右边的空格

Array.prototype.flat 与 flatMap

const arr = [1,2,3,[4,5,[6,7,8]]];
let result1 = arr.flat(); // 将三维数组解析为二维数组
let result2 = arr.flat(2); // 将三维数组解析为一维数组,参数:解析的深度。不写时默认为1
console.log(result1);
console.log(result2);

Insert image description here

const arr = [1, 2, 3, 4];
const result1 = arr.map(item => [item * 10]);
const result2 = arr.flatMap(item => [item * 10]);
console.log(result1);
console.log(result2);

Insert image description here

ES11

Class private properties

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);
	}
}
let p = new Person('孙悟空', 18, 99);
console.log(p.name);
p.intro(); // 但是可以在函数内部调用私有属性
console.log(p.#age); // 私有属性不能在外部调用,会报错

Insert image description here

Promise.allSettled 和 Promise.all

Promise.allSettled always returns a successful promise object
Promise.all. When the status of the incoming promise object is successful, a successful promise object is returned, otherwise a failed promise object is returned.

let p1 = new Promise((resolve, reject) => {
    
    
	resolve('成功111');
})
let p2 = new Promise((resolve, reject) => {
    
    
	reject('失败222');
})
const result = Promise.allSettled([p1, p2]);
const result1 = Promise.all([p1, p2]);
console.log(result);
console.log(result1);

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_46683645/article/details/118225037