1. 迭代器
什么是迭代器
迭代器(Iterator)就是一种机制。它是一种接口,为各种不同的数据结构提供统一的访问机制。任何数据结构只要部署 Iterator 接口,就可以完成遍历操作。
ES6 创造了一种新的遍历命令 for…of 循环,Iterator 接口主要供 for…of 消费
原生具备 iterator 接口的数据(可用 for of 遍历)
- Array
- Arguments
- Set
- Map
- String
- NodeList
工作原理
-
创建一个指针对象,指向当前数据结构的起始位置
-
第一次调用对象的 next 方法,指针自动指向数据结构的第一个成员
-
接下来不断调用 next 方法,指针一直往后移动,直到指向最后一个成员
-
每调用 next 方法返回一个包含 value 和 done 属性的对象
-
注: 需要自定义遍历数据的时候,要想到迭代器
- Set
ES6 提供了新的数据结构 Set(集合)。它类似于数组,但成员的值都是唯一的,集合实现了 iterator 接口,所以可以使用『扩展运算符』和『for…of…』进行遍历,集合的属性和方法: -
size 返回集合的元素个数
-
add 增加一个新元素,返回当前集合
-
delete 删除元素,返回 boolean 值
-
has 检测集合中是否包含某个元素,返回 boolean 值
-
clear 清空集合,返回 undefined
<script>
//set 的元素是唯一的
const s1 = new Set([1, 2, 3, 4, 5, 1, 3, 5]);
console.log(s1);
// - size 返回 Map 的元素个数
console.log(s1.size);
//add增加一个新的元素,返回当前合集
console.log(s1.add(100));
//delete 删除元素,返回boolean值
console.log(s1.delete(100));
// - has 检测 Map 中是否包含某个元素,返回 boolean 值
console.log(s1.has(100));
// - clear 清空集合,返回 undefined
console.log(s1.clear());
</script>
## map
ES6 提供了 Map 数据结构。它类似于对象,也是键值对的集合。但是“键” 的范围不限于字符串,各种类型的值(包括对象)都可以当作键。Map 也实现了 iterator 接口,所以可以使用『扩展运算符』和『for…of…』进行遍历。Map 的属性和方法:
const obj = {
name: '张三'
}
const m = new Map([
['name', 'admin']
], [obj, '哈哈']);
console.log(m);
// - size 返回 Map 的元素个数
console.log(m.size);
// - set 增加一个新元素,返回当前 Map
console.log(m.set('age', 18));
// - get 返回键名对象的键值
console.log(m.get('age'));
// - has 检测 Map 中是否包含某个元素,返回 boolean 值
console.log(m.has('age'));
// - clear 清空集合,返回 undefined
console.log(m.clear());
2.class类
ES6 提供了更接近传统语言的写法,引入了 Class(类)这个概念,作为对象的模板。通过 class 关键字,可以定义类。基本上,ES6 的 class 可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的 class 写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。知识点:
- class 声明类
- constructor 定义构造函数初始化
- extends 继承父类
- super 调用父级构造方法
- static 定义静态方法和属性
- 父类方法可以重写
<script>
//声明一个类
class phone {
//构造函数:初始化
constructor(brand, color, price) {
this.brand = brand
this.color = color
this.price = price
}
photo() {
console.log('照相');
}
game() {
console.log(this.brand, '我可以打游戏');
}
}
const p = new phone('华为', '黑色', 4999);
console.log(p);
p.photo();
p.game();
</script>
2.1继承
<script>
//父类
class phone {
//构造函数:初始化
constructor(brand, color, price) {
this.brand = brand
this.color = color
this.price = price
}
photo() {
console.log('照相');
}
game() {
console.log(this.brand, '我可以打游戏');
}
}
//子类
class smartphone extends phone {
constructor(brand, color, price) {
//super调用父类的构造化 进行初始化 当实现了constructor()构造函数,super必须调用
super(brand, color, price);
this.screen = screen;
}
}
const sp = new smartphone('华为', '黑色', 4999, '6.1');
console.log(sp);
sp.photo();
</script>
2.2 staice
<script>
class Person {
//static静态 修饰
static type = 'human';
static SayHi() {
console.log('hello');
}
};
//被static修饰的属性叫静态属性
//被static修饰的方法叫静态方法
//使用类名直接调用,不需要实例化(new对象)
console.log(Person.type);
Person.SayHi();
</script>