es6基础(2)

es6标准入门

Iterator

遍历器接口

1
2
3
4
5
6
7
8
let s = function* (){
yield '🍨';
yield '🍔'
}
const r = s()
console.log(r.next())
console.log(r.next())
console.log(r.next())

上面用的不多

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const arr = ['🍐','🍊','🥭']
// for of直接得到值
for(let v of arr){
console.log(v)
}
// for in得到索引
for(let i in arr){
console.log(i)
}

// 🍐
// 🍊
// 🥭
// 0
// 1
// 2

const obj = {
a: '🍐',
b: '🍊',
c: '🥭'
}
for(let v of obj){
console.log(v)
}
// VM289:6 Uncaught TypeError: obj is not iterable

Generator

Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Person{
constructor(age){
this.age = age
}
}
const xiaowang = new Person(30)
console.log(xiaowang.age)
// 30
// 新的代码块
class Person{
constructor(age){
this.age = age
}
tell(){
console.log(`小王的年龄是${this.age}`)
}
}
class Man extends Person{
constructor(age){
super(age)
this.arr = []
}
tell(){
super.tell()
console.log('halo')
}
set menu(data){
this.arr.push(data)
}
get menu(){
return this.arr
}
static init(){
console.log('static')
}
}
Man.init()
const xiaowang = new Man(30)
console.log(xiaowang.tell())
xiaowang.menu = '🍅'
console.log(xiaowang.menu)
// static
// 小王的年龄是30
// halo
// ["🍅"]

Set Map

Set

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
let arr = new Set('🍦🍔🥪')
arr.add('🌭')
arr.add('🍲')
arr.add('🍲')
console.log(arr)
console.log(arr.has('🍔'))
arr.delete('🍔')
for(let t of arr){
console.log(t)
}
arr.clear()
console.log(arr)

// Set(5) {"🍦", "🍔", "🥪", "🌭", "🍲"} 自动去重
// true
// 🍦
// 🥪
// 🌭
// 🍲
// Set(0) {}

Map

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
let food = new Map()
let fruit = {},cook = function (){}
food.set(fruit,'🍋')
food.set(cook,'🍔')
console.log(food)
console.log(food.get(fruit))
console.log(food.size)
food.delete(fruit)
console.log(food.size)
food.clear()
console.log(food.size)

// Map(2) {{…} => "🍋", ƒ => "🍔"}
// [[Entries]]
// 0: {Object => "🍋"}
// key: {}
// value: "🍋"
// 1: {function (){} => "🍔"}
// key: ƒ ()
// value: "🍔"
// size: (...)
// __proto__: Map
// 🍋
// 2
// 1
// 0

数组去重

1
2
3
4
const arr = [1,2,3,4,4,4,5]
const r = [...new Set(arr)]
console.log(r)
// (5) [1, 2, 3, 4, 5]

Moudle

index.js

1
2
3
4
5
6
7
8
9
10
11
const test  =  function test(arg){
// xxx
}
export test

const go = function go(arg){
// xxx
}
export go
// 或 exprot {test, go}
// export default

run.js

1
2
3
4
import {test, go} from 'index.js'
// import data from 'index.js'
// data.test()
// data.go()