<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>generator生成器</title>
</head>
<body>
<script>
/*
* generator生成器
* 可以返回多次的函数
*/
// 迭代器还原生成器的解构
function nameIterator (names) {
let nextIndex = 0;
return {
next: function () {
return nextIndex < names.length?
{value: names[nextIndex],done:false} :
{value: "undefined",done:true}
}
}
}
const nameArray = ["Henry","Bucky","Emily"];
const names = nameIterator(nameArray);
console.log(names.next());
console.log(names.next());
// es6 使用生成器实现id自增
function* createIds () {
let id = 1;
while (true) {
yield id++;
}
}
let gen = createIds();
for(let i=0;i<10;i++){
console.log(gen.next().value);
}
</script>
</body>
</html>
es6 generator原理解析
最新推荐文章于 2022-07-18 14:16:08 发布