解説
ジェネレータ(generator)は、値を生成する特殊な関数などのことです。処理を途中で止めて値を返すyieldといった仕組みを持っており、状態を保持して値を返す処理を、簡潔に書くことができます。
ジェネレータは、イテレータの一種でもあります。
サンプル
「ジェネレータ」のサンプルです。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>「ジェネレータ」のサンプル</title>
<style> #output { font-size: 32px; line-height: 1.5; white-space: pre-wrap; } </style>
</head>
<body>
<pre id="output"></pre>
<script>
window.addEventListener('DOMContentLoaded', e => {
// 出力用の関数
const print = function() {
const el = document.querySelector('#output');
el.textContent += [...arguments].map(x => {
if (x !== null && typeof x === 'object') {
return '{ ' + Object.entries(x).map(y => `${y[0]}: ${y[1]}`).join(', ') + ' }'
}
return `${x}`;
}).join(', ') + '\n';
};
// ジェネレータ
function* range(from, to) {
let i = from;
while (i <= to) {
yield i ++;
}
}
print('ジェネレータの利用1');
for (let i of range(2, 4)) {
print(i);
}
print('\nジェネレータの利用2');
let r = range(3, 5);
print(r.next());
print(r.next());
print(r.next());
print(r.next());
});
</script>
</body>
</html>
ジェネレータの利用1
2
3
4
ジェネレータの利用2
{ value: 3, done: false }
{ value: 4, done: false }
{ value: 5, done: false }
{ value: undefined, done: true }
フィードバックお待ちしております!
ご感想、解説してほしい用語、解説内容のアドバイスなどございましたら、FacebookやX(旧Twitter)などでお気軽に編集部までお寄せください。よろしくお願いいたします。
