blob: 3a182f7fa3ae95bcb17e8ed426d00c6877d64eed (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
---
title: Generator
slug: Web/JavaScript/Reference/Global_Objects/Generator
tags:
- Class
- ECMAScript 2015
- Generator
- JavaScript
- Legacy Generator
- Legacy Iterator
- Reference
translation_of: Web/JavaScript/Reference/Global_Objects/Generator
---
<div>{{JSRef}}</div>
<p><code><strong>Generator</strong></code> オブジェクトは{{JSxRef("Statements/function*", "ジェネレーター関数", "", 1)}}によって返され、<a href="/ja/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol">反復可能プロトコル</a>と<a href="/ja/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterator_protocol">反復子プロトコル</a>の両方に準拠しています。</p>
<h2 id="Constructor" name="Constructor">コンストラクター</h2>
<p>このオブジェクトを直接インスタンス化することはできません。代わりに、<a href="/ja/docs/Web/JavaScript/Reference/Statements/function*">ジェネレーター関数</a>から <code>Generator</code> のインスタンスを返すことができます。</p>
<pre class="syntaxbox notranslate">function* generator() {
yield 1;
yield 2;
yield 3;
}
const gen = generator(); // "Generator { }"</pre>
<h2 id="Instance_methods" name="Instance_methods">インスタンスメソッド</h2>
<dl>
<dt>{{JSxRef("Generator.prototype.next()")}}</dt>
<dd>{{JSxRef("Operators/yield", "yield")}} 式で得られた値を返します。</dd>
<dt>{{JSxRef("Generator.prototype.return()")}}</dt>
<dd>与えられた値を返し、ジェネレーターを終了します。</dd>
<dt>{{JSxRef("Generator.prototype.throw()")}}</dt>
<dd>ジェネレーターにエラーを投げます。(そのジェネレーターの中からキャッチされない限り、ジェネレーターも終了します)</dd>
</dl>
<h2 id="Examples" name="Examples">例</h2>
<h3 id="An_infinite_iterator" name="An_infinite_iterator">無限イテレーター</h3>
<pre class="brush: js; notranslate">function* infinite() {
let index = 0;
while (true) {
yield index++;
}
}
const generator = infinite(); // "Generator { }"
console.log(generator.next().value); // 0
console.log(generator.next().value); // 1
console.log(generator.next().value); // 2
// ...</pre>
<h2 id="Specifications" name="Specifications">仕様</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">仕様書</th>
</tr>
<tr>
<td>{{SpecName('ESDraft', '#sec-generator-objects', 'Generator objects')}}</td>
</tr>
</tbody>
</table>
<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザー実装状況</h2>
<p>{{Compat("javascript.builtins.Generator")}}</p>
<h2 id="See_also" name="See_also">関連情報</h2>
<ul>
<li>{{JSxRef("Statements/function*", "function*")}}</li>
<li>{{JSxRef("Operators/function*", '<code>function*</code> 式', "", 1)}}</li>
<li>{{JSxRef("GeneratorFunction")}}</li>
<li><a href="/ja/docs/Web/JavaScript/Guide/The_Iterator_protocol">反復処理プロトコル </a></li>
</ul>
|