介绍
本文是在学习ES6时做的一些学习笔记,所有的笔记请查看:
Iterator
Iterator是一种接口,为各种不同的数据结构提供统一的访问机制。任何数据结构只要部署Iterator接口,就可以完成遍历操作(即一次处理该数据结构的所以成员)。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Iterator</title>
</head>
<style>
</style>
<body>
<script>
Array.prototype.values = function(){
let i = 0;
let items = this;
return{
next(){
const done = i>items.length;
const value = done?undefined:items[i++];
return {
value;
done
}
}
}
}
const colors=['red','blue','green']
const iterator=colors.entries();
iterator.next()
const iterator = colors.keys()
iterator.next()
const iterator = color.values()
iterator.next()
</script>
</body>
</html>
Generator:
生成器是一种返回迭代器的函数,通过function关键字后的星号(*)来表示,函数中会用到新的关键字yield。星号可以紧挨着function关键字,也可以在中间添加一个空格
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Generator</title>
</head>
<body>
<script>
function* listColors(){
yield 'red';
yield 'green';
yield 'blue';
}
function* listColorsindex(){
let i;
yield i;
i++;
yield i;
i++;
yield i;
}
const color=listColrs();
color.next();
color.next();
color.next();
const colorindex=listColorsindex();
colorindex.next()
colorindex.next()
colorindex.next()
const owners = [
{name: 'mojombo',location: 'San Franciso', followers: 123},
{name: 'vanpelt',location: 'Bay Minette', followers: 1034}.
{name: 'wycats',location: 'Los Angeles,CA', followers: 388}
]
function* loop(arr){
for(let owner of arr){
yield owner;
}
}
const ownersloop=loop(owners);
ownersloop.next()
</script>
</body>
</html>
Generator 应用:控制ajax工作流
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Spread operator Intro</title>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<script>
function ajax(url){
axios.get(url).then(res => userGen.next(res.data));
}
function* step(){
const users=yield ajax('https://api.github.com/users');
const firstUser=yield ajax(`https://api.github.com/users/${users[0].login}`)
const followers=yield ajax(firstUser.followers_url);
}
const userGen = steps();
userGen.next()
</script>
</body>
</html>