<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
// 迭代器还原生成器的结构
function nameTterator(names) {
let nextIndex = 0
return {
next: function(){
return nextIndex < names.length ?
{value: names[nextIndex++], done: false} :
{value: undefined, done: true}
}
}
}
const nameArray = ["xiaohua", "xiaoming", "join"]
const names = nameTterator(nameArray)
console.log(names.next())
console.log(names.next())
console.log(names.next())
console.log(names.next())
console.log(names.next())
// 生成器的实现
function* sayNames(){
yield 'xiaohua'
yield 'xiaoming'
yield 'join'
}
const name = sayNames()
console.log(name.next())
console.log(name.next())
console.log(name.next())
console.log(name.next())
console.log(name.next())
// ID 自增 (es 生成器)
function* createIds(){
let index = 1
while (true){
yield index++
}
}
const gen = createIds()
for (let i = 0; i < 10; i++){
console.log(gen.next().value)
}
</script>
</head>
<body>
</body>
</html>
JavaScript生成器和迭代器
最新推荐文章于 2023-04-23 22:20:02 发布