ES6 内容总结
1.迭代器
迭代器(Iterator)是一种接口,为各种不同的数据结构提供统一的访问机制,任何数据结构只要部署Iterator 接口,就可以完成遍历操作。
原生具备 Iterator 接口的数据(可用for of 遍历)
- Array
- Arguments
- Set
- Map
- String
- TypedArray
- NodeList
//自定义遍历数据,要想到迭代器
const xiyou = [1, 2, 3, 4, 5]
let iterator = xiyou[Symbol.iterator]();
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
迭代器应用:
//自定义遍历数据
const xiyou = {
name: "abbaba",
stus: [
'a',
'b',
'c',
'd'
],
[Symbol.iterator]() {
let that = this
let index = 0;
return {
next: function () {
if (index < that.stus.length) {
const res = { value: that.stus[index], done: false }
index++;
return res
}
else {
return { value: 'undefined', done: true }
}
}
}
}
}
for (let v of xiyou) {
console.log(v);
}
2.生成器
生成器函数是ES6提供的一种异步编程解决方案,语法行为与传统函数完全不同
function* gen() {
console.log('a');
}
let iterator = gen();
iterator.next();
=======================================================
function* gen() {//yield 函数分隔符
console.log(111);
yield `a`;
console.log(121);
yield `b`;
console.log(131);
yield `c`;
console.log(141);
}
let iterator = gen();
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
for (const i of gen()) { //遍历的是gen()里的value值
console.log(i + 9);
}
可传参数
function* gen(arg) {
console.log(arg);
let one = yield `a`;
console.log(one);
}
let iterator = gen('aaa');
console.log(iterator.next());
console.log(iterator.next('ccc'));
案例
//异步编程 1s后控制台输出 111 ,2s后输出 222 ,3s后输出 333
//1s后控制台输出 111 ,2s后输出 222 ,3s后输出 333
function one() {
setTimeout(() => {
console.log(111);
itrerator.next()
}, 1000)
}
function two() {
setTimeout(() => {
console.log(222);
itrerator.next()
}, 2000)
}
function three() {
setTimeout(() => {
console.log(333);
}, 3000)
}
function* gen() {
yield one();
yield two();
yield three();
}
let itrerator = gen();
itrerator.next()
案例 模拟数据 用户数据 订单数据 商品数据
function one() {
setTimeout(() => {
let data = '用户数据'
itrerator.next(data)
}, 1000)
}
function two() {
setTimeout(() => {
let data = '订单数据'
itrerator.next(data)
}, 1000)
}
function three() {
setTimeout(() => {
let data = '商品数据'
itrerator.next(data)
}, 1000)
}
function* gen() {
let user = yield one();
console.log(user);
let dingdan = yield two();
console.log(dingdan);
let goods = yield three();
console.log(goods);
}
let itrerator = gen();
itrerator.next()