ECMAScript 6.0

1. let declare variables

  1. block scope
  2. Duplicate declarations are not allowed
  3. Variable promotion has no
    temporal dead zone
  4. not hooked to the top-level object

2. const declares constants

  1. constant
  2. Cannot be defined repeatedly
  3. block level
  4. statement does not raise
  5. not hooked to the top-level object
  6. Object.freeze() freezes object properties

3. Variable deconstruction assignment

Destructuring assignment is a grammatical way to quickly extract members from objects, arrays or strings.
Quickly
obtain members from objects

// ES5的方法向得到对象中的成员
const obj = {
    
    
	name: 'kerwin' ,
	age: 100,
	gender: '男'
}
let name = obj.name
let age = obj.age
let gender = obj.gender
//解构赋值的方式从对象中获取成员
const obj = {
    
    
	name: 'kerwin',
	age: '100',
	gender: '男'
}
let {
    
    name,age,gender}=obj;

4. String and numeric extensions

(1) String expansion

  1. The includes function
    determines whether a specified character exists in a string
let myname = "kerwin"
console.log(myname . includes("e")) //true
console.log (myname . startswith("k")) //true
console.log(myname . endswith("n")) //true
  1. repeat function
    The repeat() method returns a new string, which means repeating the original string n times.
let myname = "kerwin"
console.log(myname. repeat(3)) //kerwinkerwinkerwin
console.log(myname . repeat(0)) //""
console.log (myname . repeat(3.5)) //kerwinkerwinkerwin
console.log(myname . repeat("3"))//kerwinkerwinkerwin

(2) Numerical extension

  1. binary and octal notation
let count1 = 100
let count2 = 0x100
let count3 = 0o100
let count4 = 0b100
  1. The isFinite and isNaN methods
    reduce global methods and make the language gradually modular
let num1 = Number. isFinite(100) //true
let num2 = Number. isFinite(100/0) //false
let num3 = Number. isFinite(Infinity) // false
let num4 = Number. isFinite("100") //false
let num1 = Number. isNaN(100) // false
let num2 = Number. isNaN(NaN) //true
let num3 = Number . isNaN("kerwin") //false
let num4 = Number. isNaN("100") // false

The difference between them and the traditional global methods isFinite() and isNaN() is that the traditional methods first call Number() to convert non-numeric values ​​into numerical values, and then make judgments, while these two new methods are only valid for numerical values, Number. isFinite() returns false for all non-numeric values, Number.isNaN) returns true only for NaN, and returns false for all non-NaN values.

  1. The isinteger method
    is used to determine whether a value is an integer.
let num1 = Number. isInteger(100) //true
let num2 = Number. isInteger(100.0) //true
let num3 = Number. isInteger("kerwin") //false
let num4 = Number . isInteger("100") //false
  1. The minimal constant Number.EPSILON
    which represents the difference between 1 and the smallest floating-point number greater than 1. 2.220446049250313e-16
function isEqual(a,b){
    
    
	return Math.abs(a-b)<Number . EPSILON
}
console.log(isEqual(0.1+0.2,0.3)) //true
console.log(0.1+0.2===0.3) //false
  1. Math.trunc
    erases the decimal part and returns an integer.
console.log(Math. trunc(1.2)) //1
console.log(Math. trunc(1.8)) //1
console.log(Math. trunc(-1.8)) //-1
console.log(Math.trunc(-1.2)) //-1
  1. Math.sign
    The Math.sign method is used to determine whether a number is positive, negative, or zero. For non-numeric values, it is first converted to a numeric value.
Math. sign(-100) // -1
Math. sign(100) // +1
Math. sign(0) // +0
Math. sign(-0) // -0
Math. sign("kerwin") // NaN

5. Array expansion

  1. spread operator
let arr1 = [1,2,3]
let arr2 = [4,5,6]
console.log([...arrl,...arr2])
  1. Array.from
    converts an array-like object to a real array
function test(){
    
    
	console.log(Array. from(arguments))
}
test(1,2,3)
let oli = document. queryselectorAll("li")console.log(Array. from(oli))
  1. Array.of
    converts a set of values ​​into an array, that is, a new array
let arr1 = Array(3)
console.log(arr1)// [,,]
let arr2 = Array.of(3)console.log(arr2)// [3]
  1. find method
    1) This method is mainly used to find the first qualified array element
    2) Its parameter is a callback function. In the callback function, you can write the condition of the element you want to find. When the condition is true, return the element. If there is no eligible element, the return value is undefined
  2. findIndex()
  3. findLast findLastIndex() ES2022
  4. fill
  5. flat() flatMap() flattening

6. Object extension

  1. object shorthand
  2. object property expression
  3. The spread operator... ES2018
  4. Object.assign
  5. Object.is judges whether it is equal

7. Function extension

  1. parameter default value
  2. rest parameter rest parameter
  3. name attribute
  4. Arrow function: Introduction to writing
    ()=>{}
    (1) Only return can be omitted
    (2) If the object is returned, attention should be paid
    (3) If there is only one parameter, () can be omitted
    (4) Arguments cannot be accessed and new
    (5) The arrow does not have this, this points to the parent scope

8、Symbol

ES6 introduces a new primitive data type symbol, which represents a unique value. It belongs to one of the native data types of the JavaScript language, other data types are: undefined, null, Boolean (Boolean), string (String), value (Number), object (Object).

  1. Use Symbol as object property name
let name = Symbol()//生成了一个symbol类型数据
let age = Symbol()
var obj ={
    
    
	[name]:"kerwin",
	[age] :100
}
  1. The Symbol() function can accept a string as a parameter, representing the description of the Symbol instance. This is mainly for display on the console, which is easier to distinguish.
let name = Symbol("name ")
let age = Symbo1("age")
var obj={
    
    
	[name]: "kerwin",
	[age] :100
}
console.log(obj)
  1. Symbol.for() can reuse the same Symbol value
var obj ={
    
    
	[symbol. for("name ")]: "kerwin",
	[symbol. for("age ")]:100
}
console.log(obj[symbol.for("name")])

Note:

  1. cannot perform calculations
  2. Show calls toString()
  3. Implicit conversion boolean

9. Iterator Iterator

Iterator has three functions:
one is to provide a unified and convenient access interface for various data structures; the
other is to enable the members of the data structure to be arranged in a certain order;
the third is ES6 to create a new traversal command for ...of cycle, the iterator interface is mainly for for...of cycle

let arr = ["kerwin""tiechui", "gangdaner"]
for(let i of arr){
    
    
	console.log(i)
}
Iterator的遍历过程是这样的。
(1)创建一个指针对象,指向当前数据结构的起始位置。也就是说,遍历器对象本质上,就是一个指针对象。
(2)第一次调用指针对象的next方法,可以将指针指向数据结构的第一个成员。
(3)第二次调用指针对象的next方法,指针就指向数据结构的第二个成员。
(4)不断调用指针对象的next方法,直到它指向数据结构的结束位置。
let i = arr[symbol. iterator]()
console.log(i. next())
console.log(i. next())
console.log(i. next())
console.log(i. next())

ES6 stipulates that the default Iterator interface is deployed in the Symbol.iterator property of the data structure. In other words, as long as a data structure has the Symbol.iterator property, it can be considered "traversable" (iterable). The Symbol.iterator property itself is a function, which is the default traverser generation function of the current data structure. Executing this function will return a traverser.

The default data structure with the Iterator interface is as follows.

  • Array
  • Set
  • Map
  • String
  • arguments object.
  • NodeList object

How to perform for fo traversal on objects?

let obj ={
    
    
	0: "kerwin",
	1: "tiechui",
	2: "gangdaner",
	length: 3,
	[Symbol.iterator]: Array.prototype[Symbol.iterator]
}
for(let i of obj) {
    
    
	console.log(i)
}
let obj2 = {
    
    
	data: ['kerwin', 'tiechuiI, "gangdaner"],
	[Symbol. iterator](){
    
    
		//let _this=this
		let index=0;
		return {
    
    
			next:()=>{
    
    
				if (index < this. data.1ength)
				return {
    
    
					value: this. data[index++],
					done: false
				}
			}else{
    
    
				return {
    
    
					value: undefined,
					done: true
				}
			}
		}
	}
}
for (let i of obj2) {
    
    
	console. log(i)
}

10. Set structure

It is similar to an array, but the values ​​of the members are all unique and there are no duplicate values.

(1). Getting to know Set for the first time

let s1 = new Set([1, 23, 23])
console. log(s1)
let s2 = new Set()
s2. add(1)
s2. add(2)
s2. add(3)
console.log(s2)

(2). Attributes and methods of instances

  • size: Returns the total number of members of the Set instance.
  • Set.prototype.add(value): Add a value.
  • Set.prototype.delete (va1ue): Delete a value and return a Boolean value indicating whether the deletion is successful.
  • Set.prototype.has(value) : Returns a boolean indicating whether the value is a member of the set.
  • Set.prototype.clear(): Clear all members, no return value.

(3). Traverse

  • Set.prototype.keys() : returns a traverser of key names
  • Set.prototype.values() : returns a traverser of key values
  • Set.prototype.entries() : returns a traverser of key-value pairs
  • Set.prototype.forEach()): traverse each member

11. Map structure

Similar to objects, it is also a collection of key-value pairs, but the scope of "keys" is not limited to strings, and various types of values ​​(including objects) can be used as keys.

(1) Getting to know Map for the first time

let m1 = new Map()
m1.set("name", "kerwin")
m1.set({
    
    a:1},"大连")
console. 1og(m1)
let m2= new Map([
	["name""kerwin"][{
    
    a:1},"大连"]
])
console.log(m2)

(2) Properties and methods of instances

  • size: Returns the total number of members of the Map structure.
  • Map.prototype.set(key, value) : add the value corresponding to the key, and return the Map structure itself.
  • Map.prototype.get(key) : Get the value corresponding to the key
  • Map.prototype.delete(key) : Delete a key (key name + key value)
  • Map.prototype.has(key) : Whether a certain key is in the current Map object.
  • Map.prototype.keys(): Returns a iterator of key names.
  • Map.prototype.values(): returns a traverser of key values.
  • Map.prototype.entries(): returns a traverser for all members
  • Map.prototype.forEach(): traverse all members of Map

12. Proxy agent

Proxy, as its name suggests, is to set up a proxy between the object and its attribute value, get the value of the object or set the value of the object, and various operations such as instantiation will be intercepted. After this We can deal with one layer in a unified way, we can think of it as "agent"

  1. get method
let target = {
    
    }
let proxy = new Proxy(target,{
    
    
	get(target, prop){
    
    
		return target[prop]
	}
})
  1. set method

Proxy is essentially a meta-programming non-destructive data hijacking. The function is derived on the basis of the original object without affecting the original object, which conforms to the design concept of loose coupling and high cohesion.

13. Reflect object

Reflect can be used to obtain the behavior of the target object. It is similar to Object, but it is more readable and provides a more elegant way to manipulate objects. Its method corresponds to Proxy.

(1) Replace some methods of Object

const obj = {
    
    
};
Reflect. defineProperty(obj, 'name', {
    
    
	value: 'kerwin',
	writable: false ,
	configurable:fa1se
});

(2) Modify some Object methods to return results

//老写法
try {
    
    
	Object. defineProperty(target, property, attributes);
	// success
} catch (e) {
    
    
// fail
}
//新写法
if (Reflect. defineProperty(target, property, attributes)) {
    
    
	// success
} e1se {
    
    
	// fail
}

(3) Imperative becomes functional behavior

const obj = {
    
    
	name : "kerwin"
};
//老写法
console.log("name" in obj) //true
//新写法
console.log(Reflect. has(obj,'name')) //true
//老写法
delete obj . name
//新写法
Reflect. deleteProperty(obj, "name")

(4) Cooperate with Proxy

let target = new Set()
const proxy = new Proxy(target, {
    
    
	get(target, key) {
    
    
		const value = Reflect . get(target ,key)
		// 遇到Function都手动绑定一下this
		if (value instanceof Function) {
    
    
			console.log(`访问${
      
      value}方法了`)
			return value. bind(target)
			//不能 是 call apply
		}
		return value
	},
	set() {
    
    
		return Reflect. set(...arguments)
	}
})
proxy. add(1)
let arr=[1,2,3]
let proxy = new Proxy(arr,{
    
    
	get(target, key) {
    
    
		console.log('get', key)
		return Reflect. get(...arguments)
	},
	set(target, key, value) {
    
    
		console. log('set', key, value)
		return Reflect.set(...arguments)
	}
})
proxy . push(4)
//能够打印出很多内容
//get push (寻找proxy.push 方法)
//get length (设置当前的length)
//set 3 4(设置proxy[3]=4)
//set length 4 (设置proxy. length = 4)

14、Promise

Promise is a solution to asynchronous programming, which is more reasonable and powerful than the traditional solution callback function. ES6 writes it into the language standard, unifies usage, and provides Promise objects natively.

  • The method of specifying the callback function is more flexible and understandable.
  • Solve the problem of asynchronous callback hell .

Promise.all
Promise.race

(1) Callback hell

  • When a callback function nests a callback function
  • A nested structure will appear
  • When there is too much nesting, there will be callback hell
  • For example, if we send three ajax requests,
    the first one is sent normally
    and the second request requires a value from the result of the first request as a parameter.
    The third request requires a value from the result of the second request as a parameter
  • Callback hell is actually caused by too much nesting of callback functions
  • When the code becomes this structure, there is no possibility of maintenance

(2) Promise use

grammar:

new Promise(function (resolve, reject) {
	// resolve表示成功的回调
	// reject表示失败的回调
}). then(function (res) {
	//成功的函数
}). catch(function (err) {
	// 失败的函数
})

(3) The state of the Promise object

Promise objects control asynchronous operations through their own state. A Promise instance has three states.

Asynchronous operation pending (pending)
Asynchronous operation successful (fulfilled)
Asynchronous operation failed (rejected)

There are only two ways to change these three states.

From "incomplete" to "success"
from "incomplete" to "failure"

Once the state changes, it is frozen, and there will be no new state changes. This is also the origin of the name Promise, which means "promise" in English. Once the promise is fulfilled, it cannot be changed. This also means that the state change of a Promise instance can only happen once.
Therefore, there are only two final results of Promise.

If the asynchronous operation succeeds, the Promise instance returns a value (value), and the state becomes fulfilled. If the
asynchronous operation fails, the Promise instance throws an error (error), and the state becomes rejected.

15. Generator function

The Generator function is an asynchronous programming solution provided by ES6.
The Generator function is a state machine that encapsulates multiple internal states.
Executing the Generator function will return a traverser object, that is to say, the Generator function is not only a state machine, but also a traverser object generation function. The returned traverser object can traverse each state inside the Generator function in turn.

(1) Basic grammar

function *gen(){
    
    
	console. log(1)
	yield;
	console. log(2)
	yield;
	console. log(3)
}
let g = gen()
g.next()
g.next()
g.next()

The yield (output) expression is a marker to suspend execution, and the next method can resume execution.

(2) Asynchronous process

manual version

function *gen() {
    
    
	let res1 = yield ajax("1. json")
	console.log(res1)
	let res2 = yield ajax("2. json")
	console.log(res2)
}
let g = gen()
g. next(). value. then(data=>{
    
    
	g. next(data). value. then(data=>{
    
    
		g. next(data)
	})
})

automatic version

function* gen() {
    
    
	let res1 = yie]d ajax("1. json")
	console. log(res1)
	let res2 = yie1d ajax("2. json")
	console. log(res2)
}
function AutoRun(gen) {
    
    
	let g = gen();
	function next(data) {
    
    
		let res = g.next(data);
		if (res. done) return
		res. value. then(function (data) {
    
    
			next (data);
		});
	}
	next();
}
AutoRun(gen) ;

16. Class syntax

(1) Class writing

class Person{
    
    
	constructor(name ,age){
    
    
		this. name = name;
		this.age = age;
	}
	sayOf(){
    
    
		console.log(this. name , this. age)
	}
}
let obj = new Person("kerwin" ,100)
console.log(obj)

(2) getter与setter

17. Module syntax

Modularity,
asynchronous loading,
no privacy,
no fear of duplicate names,
no messy dependencies

18. Modularity in NodeJS

JavaScript now has two kinds of modules. One is the ES6 module, referred to as ESM; the other is the CommonJS module, referred to as CJS
Common]S module is dedicated to Node.js and is not compatible with ES6 modules. In terms of syntax, the most obvious difference between the two is that CommonJS modules use require() and module. exports , while ES6 modules use import and export.

The ES6 module is not an object, but the code that is explicitly specified for output through the export command, and then imported through the import command.
Writing 1:

export default A1
import a1 from "./1.js"

Writing 2:

export {
    
    A1,A2}
import {
    
    A1,A2} from "./1.js"
import {
    
    Al as a1,A2 as a2} from "./1.js"
import * as obj from "./1.js"

おすすめ

転載: blog.csdn.net/ZiminLi/article/details/128811013