aboutsummaryrefslogtreecommitdiff
path: root/files/ru/web/javascript/reference/global_objects/generator
diff options
context:
space:
mode:
authorPeter Bengtsson <mail@peterbe.com>2020-12-08 14:42:52 -0500
committerPeter Bengtsson <mail@peterbe.com>2020-12-08 14:42:52 -0500
commit074785cea106179cb3305637055ab0a009ca74f2 (patch)
treee6ae371cccd642aa2b67f39752a2cdf1fd4eb040 /files/ru/web/javascript/reference/global_objects/generator
parentda78a9e329e272dedb2400b79a3bdeebff387d47 (diff)
downloadtranslated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.gz
translated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.bz2
translated-content-074785cea106179cb3305637055ab0a009ca74f2.zip
initial commit
Diffstat (limited to 'files/ru/web/javascript/reference/global_objects/generator')
-rw-r--r--files/ru/web/javascript/reference/global_objects/generator/index.html187
-rw-r--r--files/ru/web/javascript/reference/global_objects/generator/next/index.html116
-rw-r--r--files/ru/web/javascript/reference/global_objects/generator/return/index.html95
-rw-r--r--files/ru/web/javascript/reference/global_objects/generator/throw/index.html140
4 files changed, 538 insertions, 0 deletions
diff --git a/files/ru/web/javascript/reference/global_objects/generator/index.html b/files/ru/web/javascript/reference/global_objects/generator/index.html
new file mode 100644
index 0000000000..b5fe95a5bf
--- /dev/null
+++ b/files/ru/web/javascript/reference/global_objects/generator/index.html
@@ -0,0 +1,187 @@
+---
+title: Generator
+slug: Web/JavaScript/Reference/Global_Objects/Generator
+tags:
+ - ECMAScript 2015
+ - Generator
+ - JavaScript
+ - Legacy Generator
+ - Legacy Iterator
+ - NeedsTranslation
+ - Reference
+ - TopicStub
+translation_of: Web/JavaScript/Reference/Global_Objects/Generator
+---
+<div>{{JSRef}}</div>
+
+<p><code><strong>Генератор</strong></code> - это объект, возвращаемый {{jsxref("Statements/function*", "функцией-генератором", "", 1)}} и соответствующий как <a href="/ru/docs/Web/JavaScript/Reference/Iteration_protocols#iterable">"Итерируемому" протоколу</a>, так и <a href="/ru/docs/Web/JavaScript/Reference/Iteration_protocols#iterator">протоколу "Итератор"</a>.</p>
+
+<h2 id="Синтаксис">Синтаксис</h2>
+
+<pre class="syntaxbox">function* gen() {
+ yield 1;
+ yield 2;
+ yield 3;
+}
+
+var g = gen(); // "Generator { }"</pre>
+
+<h2 id="Методы">Методы</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="Пример">Пример</h2>
+
+<h3 id="Бесконечный_Итератор">Бесконечный Итератор</h3>
+
+<pre class="brush: js">function* idMaker() {
+ var index = 0;
+ while(true)
+ yield index++;
+}
+
+var gen = idMaker(); // "Generator { }"
+
+console.log(gen.next().value); // 0
+console.log(gen.next().value); // 1
+console.log(gen.next().value); // 2
+// ...</pre>
+
+<h2 id="Legacy_generator_objects">Legacy generator objects</h2>
+
+<p>Firefox (SpiderMonkey) also implements an earlier version of generators in <a href="/en-US/docs/Web/JavaScript/New_in_JavaScript/1.7">JavaScript 1.7</a>, where the star (*) in the function declaration was not necessary (you just use the <code>yield</code> keyword in the function body). However, legacy generators are deprecated. Do not use them; they are going to be removed ({{bug(1083482)}}).</p>
+
+<h3 id="Legacy_generator_methods">Legacy generator methods</h3>
+
+<dl>
+ <dt><code>Generator.prototype.next() </code>{{non-standard_inline}}</dt>
+ <dd>Returns a value yielded by the {{jsxref("Operators/yield", "yield")}} expression. This corresponds to <code>next()</code> in the ES2015 generator object.</dd>
+ <dt><code>Generator.prototype.close()</code> {{non-standard_inline}}</dt>
+ <dd>Closes the generator, so that when calling <code>next()</code> an {{jsxref("StopIteration")}} error will be thrown. This corresponds to the <code>return()</code> method in the ES2015 generator object.</dd>
+ <dt><code>Generator.prototype.send()</code> {{non-standard_inline}}</dt>
+ <dd>Used to send a value to a generator. The value is returned from the {{jsxref("Operators/yield", "yield")}} expression, and returns a value yielded by the next {{jsxref("Operators/yield", "yield")}} expression. <code>send(x)</code> corresponds to <code>next(x)</code> in the ES2015 generator object.</dd>
+ <dt><strong><code>Generator.</code></strong><code>prototype.</code><strong><code>throw()</code> </strong> {{non-standard_inline}}</dt>
+ <dd>Throws an error to a generator. This corresponds to the <code>throw()</code> method in the ES2015 generator object.</dd>
+</dl>
+
+<h3 id="Legacy_generator_example">Legacy generator example</h3>
+
+<pre class="brush: js">function fibonacci() {
+ var a = yield 1;
+ yield a * 2;
+}
+
+var it = fibonacci();
+console.log(it); // "Generator { }"
+console.log(it.next()); // 1
+console.log(it.send(10)); // 20
+console.log(it.close()); // undefined
+console.log(it.next()); // throws StopIteration (as the generator is now closed)
+</pre>
+
+<h2 id="Specifications">Specifications</h2>
+
+<table class="standard-table">
+ <tbody>
+ <tr>
+ <th scope="col">Specification</th>
+ <th scope="col">Status</th>
+ <th scope="col">Comment</th>
+ </tr>
+ <tr>
+ <td>{{SpecName('ES2015', '#sec-generator-objects', 'Generator objects')}}</td>
+ <td>{{Spec2('ES2015')}}</td>
+ <td>Initial definition.</td>
+ </tr>
+ <tr>
+ <td>{{SpecName('ESDraft', '#sec-generator-objects', 'Generator objects')}}</td>
+ <td>{{Spec2('ESDraft')}}</td>
+ <td> </td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="Browser_compatibility">Browser compatibility</h2>
+
+<p>{{CompatibilityTable}}</p>
+
+<div id="compat-desktop">
+<table class="compat-table">
+ <tbody>
+ <tr>
+ <th>Feature</th>
+ <th>Chrome</th>
+ <th>Firefox (Gecko)</th>
+ <th>Internet Explorer</th>
+ <th>Opera</th>
+ <th>Safari</th>
+ </tr>
+ <tr>
+ <td>Basic support</td>
+ <td>{{CompatChrome(39.0)}}</td>
+ <td>{{CompatVersionUnknown}}</td>
+ <td>{{CompatNo}}</td>
+ <td>{{CompatNo}}</td>
+ <td>{{CompatNo}}</td>
+ </tr>
+ </tbody>
+</table>
+</div>
+
+<div id="compat-mobile">
+<table class="compat-table">
+ <tbody>
+ <tr>
+ <th>Feature</th>
+ <th>Android</th>
+ <th>Android Webview</th>
+ <th>Firefox Mobile (Gecko)</th>
+ <th>IE Mobile</th>
+ <th>Opera Mobile</th>
+ <th>Safari Mobile</th>
+ <th>Chrome for Android</th>
+ </tr>
+ <tr>
+ <td>Basic support</td>
+ <td>{{CompatNo}}</td>
+ <td>{{CompatChrome(39.0)}}</td>
+ <td>{{CompatVersionUnknown}}</td>
+ <td>{{CompatNo}}</td>
+ <td>{{CompatNo}}</td>
+ <td>{{CompatNo}}</td>
+ <td>{{CompatChrome(39.0)}}</td>
+ </tr>
+ </tbody>
+</table>
+</div>
+
+<h2 id="See_also">See also</h2>
+
+<h3 id="Legacy_generators">Legacy generators</h3>
+
+<ul>
+ <li>{{jsxref("Statements/Legacy_generator_function", "The legacy generator function", "", 1)}}</li>
+ <li>{{jsxref("Operators/Legacy_generator_function", "The legacy generator function expression", "", 1)}}</li>
+ <li>{{jsxref("StopIteration")}}</li>
+ <li><a href="/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features/The_legacy_Iterator_protocol">The legacy Iterator protocol</a></li>
+</ul>
+
+<h3 id="ES2015_generators">ES2015 generators</h3>
+
+<ul>
+ <li>{{jsxref("Functions", "Functions", "", 1)}}</li>
+ <li>{{jsxref("Statements/function", "function")}}</li>
+ <li>{{jsxref("Operators/function", "function expression")}}</li>
+ <li>{{jsxref("Function")}}</li>
+ <li>{{jsxref("Statements/function*", "function*")}}</li>
+ <li>{{jsxref("Operators/function*", "function* expression")}}</li>
+ <li>{{jsxref("GeneratorFunction")}}</li>
+ <li><a href="/en-US/docs/Web/JavaScript/Guide/The_Iterator_protocol">The Iterator protocol</a></li>
+</ul>
diff --git a/files/ru/web/javascript/reference/global_objects/generator/next/index.html b/files/ru/web/javascript/reference/global_objects/generator/next/index.html
new file mode 100644
index 0000000000..5e69003f85
--- /dev/null
+++ b/files/ru/web/javascript/reference/global_objects/generator/next/index.html
@@ -0,0 +1,116 @@
+---
+title: Generator.prototype.next()
+slug: Web/JavaScript/Reference/Global_Objects/Generator/next
+tags:
+ - ECMAScript6
+ - JavaScript
+ - Reference
+ - генератор
+ - метод
+ - прототип
+translation_of: Web/JavaScript/Reference/Global_Objects/Generator/next
+---
+<div>{{JSRef}}</div>
+
+<p>Метод <code><strong>next</strong></code><strong><code>()</code></strong> возвращает объект с двумя свойствами <code>done</code> и <code>value</code>. Также вы можете задать параметр для метода <code>next</code>, чтобы отправить значение в генератор.</p>
+
+<h2 id="Синтаксис">Синтаксис</h2>
+
+<pre class="syntaxbox"><code><var>gen</var>.next(value)</code></pre>
+
+<h3 id="Параметры">Параметры</h3>
+
+<dl>
+ <dt><code>value</code></dt>
+ <dd>Значение, отправляемое в генератор. Значение будет установлено в виде результата выражения yield, т. е. в [переменная] = yield [выражение] значение, которое было передано в функцию .next будет присвоено [переменной].</dd>
+</dl>
+
+<h3 id="Возвращаемое_значение">Возвращаемое значение</h3>
+
+<p><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object">Object</a></code> с двумя свойствами:</p>
+
+<ul>
+ <li><code>done</code> (boolean)
+
+ <ul>
+ <li>Имеет значение <code>true</code>, если итератор находится за окончанием итерируемой последовательности. В этом случае <code>value</code> может указывать <em>возвращаемое значение</em> итератора.</li>
+ <li>Имеет значение <code>false</code>, если итератор может создать следующее значение в последовательности. Это эквивалентно вообще не указанному свойству <code>done</code>.</li>
+ </ul>
+ </li>
+ <li><code>value</code> - любое JavaScript значение, возвращаемое итератором. Может быть опущено, когда <code>done</code> имеет значение <code>true</code>.</li>
+</ul>
+
+<h2 id="Примеры">Примеры</h2>
+
+<h3 id="Использование_next">Использование <code>next()</code></h3>
+
+<p>Следующий пример показывает простой генератор и объект, который возвращает метод <code>next</code>:</p>
+
+<pre class="brush: js">function* gen() {
+ yield 1;
+ yield 2;
+ yield 3;
+}
+
+var g = gen(); // "Generator { }"
+g.next(); // "Object { value: 1, done: false }"
+g.next(); // "Object { value: 2, done: false }"
+g.next(); // "Object { value: 3, done: false }"
+g.next(); // "Object { value: undefined, done: true }"
+</pre>
+
+<h3 id="Отправка_значения_в_генератор">Отправка значения в генератор</h3>
+
+<p>В этом примере <code>next</code> вызывается со значением. Отметим, что первый вызов ничего не вывел, потому что генератор изначально ничего не получил.</p>
+
+<pre class="brush: js">function* gen() {
+ while(true) {
+ var value = yield null;
+ console.log(value);
+ }
+}
+
+var g = gen();
+g.next(1);
+// "{ value: null, done: false }"
+g.next(2);
+// 2
+// "{ value: null, done: false }"
+</pre>
+
+<h2 id="Спецификации">Спецификации</h2>
+
+<table class="standard-table">
+ <tbody>
+ <tr>
+ <th scope="col">Спецификация</th>
+ <th scope="col">Статус</th>
+ <th scope="col">Комментарий</th>
+ </tr>
+ <tr>
+ <td>{{SpecName('ES2015', '#sec-generator.prototype.next', 'Generator.prototype.next')}}</td>
+ <td>{{Spec2('ES2015')}}</td>
+ <td>Изначальное определение</td>
+ </tr>
+ <tr>
+ <td>{{SpecName('ESDraft', '#sec-generator.prototype.next', 'Generator.prototype.next')}}</td>
+ <td>{{Spec2('ESDraft')}}</td>
+ <td></td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="Совсестимость_с_браузерами">Совсестимость с браузерами</h2>
+
+<div>
+
+
+<p>{{Compat("javascript.builtins.Generator.next")}}</p>
+</div>
+
+<h2 id="Смотрите_также">Смотрите также</h2>
+
+<ul>
+ <li><code><a href="/ru/docs/Web/JavaScript/Reference/Statements/function*">function*</a></code></li>
+ <li><a href="/ru/docs/Web/JavaScript/Guide/Iterators_and_Generators">Итераторы и генераторы</a></li>
+</ul>
diff --git a/files/ru/web/javascript/reference/global_objects/generator/return/index.html b/files/ru/web/javascript/reference/global_objects/generator/return/index.html
new file mode 100644
index 0000000000..1e77d8c64a
--- /dev/null
+++ b/files/ru/web/javascript/reference/global_objects/generator/return/index.html
@@ -0,0 +1,95 @@
+---
+title: Generator.prototype.return()
+slug: Web/JavaScript/Reference/Global_Objects/Generator/return
+translation_of: Web/JavaScript/Reference/Global_Objects/Generator/return
+---
+<div>{{JSRef}}</div>
+
+<p>Метод <code><strong>return()</strong></code> возвращает полученное значение и останавливает генератор.</p>
+
+<h2 id="Синтаксис">Синтаксис</h2>
+
+<pre class="syntaxbox"><code><var>gen</var>.return(value)</code></pre>
+
+<h3 id="Параметры">Параметры</h3>
+
+<dl>
+ <dt><code>value</code></dt>
+ <dd>Значение для возврата.</dd>
+</dl>
+
+<h3 id="Возвращаемое_значение">Возвращаемое значение</h3>
+
+<p>Значение, которое было передано в виде аргумента.</p>
+
+<h2 id="Примеры">Примеры</h2>
+
+<h3 id="Использование_return">Использование <code>return()</code></h3>
+
+<p>Следующий пример показывает простой генератор и метод <code>return</code>.</p>
+
+<pre class="brush: js">function* gen() {
+ yield 1;
+ yield 2;
+ yield 3;
+}
+
+var g = gen();
+
+g.next(); // { value: 1, done: false }
+g.return('foo'); // { value: "foo", done: true }
+g.next(); // { value: undefined, done: true }
+</pre>
+
+<p>Если <code>return(value)</code> вызывает генератор, который находится в уже "завершённом" состоянии, генератор останется в "завершённом" состоянии. Если аргумент не был передан, свойство <code>value</code> вернёт тот же объект, что и <code>.next()</code>. Если аргумент был передан, он будет установлен как значение свойства <code>value</code> возвращаемого объекта.</p>
+
+<pre class="brush: js">function* gen() {
+ yield 1;
+ yield 2;
+ yield 3;
+}
+
+var g = gen();
+g.next(); // { value: 1, done: false }
+g.next(); // { value: 2, done: false }
+g.next(); // { value: 3, done: false }
+g.next(); // { value: undefined, done: true }
+g.return(); // { value: undefined, done: true }
+g.return(1); // { value: 1, done: true }
+</pre>
+
+<h2 id="Спецификации">Спецификации</h2>
+
+<table class="standard-table">
+ <tbody>
+ <tr>
+ <th scope="col">Specification</th>
+ <th scope="col">Status</th>
+ <th scope="col">Comment</th>
+ </tr>
+ <tr>
+ <td>{{SpecName('ES2015', '#sec-generator.prototype.return', 'Generator.prototype.return')}}</td>
+ <td>{{Spec2('ES2015')}}</td>
+ <td>Изначальное определение.</td>
+ </tr>
+ <tr>
+ <td>{{SpecName('ESDraft', '#sec-generator.prototype.return', 'Generator.prototype.return')}}</td>
+ <td>{{Spec2('ESDraft')}}</td>
+ <td></td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="Совместимость_с_браузерами">Совместимость с браузерами</h2>
+
+<div>
+
+
+<p>{{Compat("javascript.builtins.Generator.return")}}</p>
+</div>
+
+<h2 id="Смотрите_также">Смотрите также</h2>
+
+<ul>
+ <li><code><a href="/ru/docs/Web/JavaScript/Reference/Statements/function*">function*</a></code></li>
+</ul>
diff --git a/files/ru/web/javascript/reference/global_objects/generator/throw/index.html b/files/ru/web/javascript/reference/global_objects/generator/throw/index.html
new file mode 100644
index 0000000000..cfdf5d3bbc
--- /dev/null
+++ b/files/ru/web/javascript/reference/global_objects/generator/throw/index.html
@@ -0,0 +1,140 @@
+---
+title: Generator.prototype.throw()
+slug: Web/JavaScript/Reference/Global_Objects/Generator/throw
+translation_of: Web/JavaScript/Reference/Global_Objects/Generator/throw
+---
+<div>{{JSRef}}</div>
+
+<p>Метод <code><strong>throw()</strong></code> возобновляет выполнение тела генератора кидая внутри исключение  <code>и возвращает объект со свойствами done и value</code>.</p>
+
+<h2 id="Синтаксис">Синтаксис</h2>
+
+<pre class="syntaxbox"><code><var>gen</var>.throw(exception)</code></pre>
+
+<h3 id="Параметры">Параметры</h3>
+
+<dl>
+ <dt><code>exception</code></dt>
+ <dd>Исключение, которое будет брошено. Во время отладки бывает полезно сделать его <code>instanceof</code> {{jsxref("Error")}}.</dd>
+</dl>
+
+<h3 id="Возвращаемое_значение">Возвращаемое значение</h3>
+
+<p>Объект с двумя свойствами:</p>
+
+<ul>
+ <li><code>done</code> (boolean)
+
+ <ul>
+ <li>Имеет значение <code>true</code> если iterator прошел конец итерируемой последовательности. В этом случае <code>value</code> опционально определяется выражением <em>return value</em> внутри итератора .</li>
+ <li>Имеет значение <code>false</code> если iterator имеет возможность вернуть следующее значение последовательности. Это равносильно когда свойство done не указано.</li>
+ </ul>
+ </li>
+ <li><code>value</code> - любое JavaScript значение,  возвращенное итератором. Может быть проигнорировано, когда <em><code>done</code> === <code>true</code></em>.</li>
+</ul>
+
+<h2 id="Примеры">Примеры</h2>
+
+<h3 id="Использование_throw()">Использование <code>throw()</code></h3>
+
+<p>В этом примере показан простой генератор и исключение,  которое выбрасывается используя метод <code>throw</code>. Исключение может быть поймано, используя, как обычно, блок <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/try...catch">try...catch</a></code>.</p>
+
+<pre class="brush: js">function* gen() {
+ while(true) {
+ try {
+ yield 42;
+ } catch(e) {
+ console.log('Error caught!');
+ }
+ }
+}
+
+var g = gen();
+g.next();
+// { value: 42, done: false }
+g.throw(new Error('Something went wrong'));
+// "Error caught!"
+// { value: 42, done: false }
+</pre>
+
+<h2 id="Спецификации">Спецификации</h2>
+
+<table class="standard-table">
+ <tbody>
+ <tr>
+ <th scope="col">Specification</th>
+ <th scope="col">Status</th>
+ <th scope="col">Comment</th>
+ </tr>
+ <tr>
+ <td>{{SpecName('ES2015', '#sec-generator.prototype.throw', 'Generator.prototype.throw')}}</td>
+ <td>{{Spec2('ES2015')}}</td>
+ <td>Initial definition.</td>
+ </tr>
+ <tr>
+ <td>{{SpecName('ESDraft', '#sec-generator.prototype.throw', 'Generator.prototype.throw')}}</td>
+ <td>{{Spec2('ESDraft')}}</td>
+ <td> </td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="Совместимость_браузеров">Совместимость браузеров</h2>
+
+<div>{{CompatibilityTable}}</div>
+
+<div id="compat-desktop">
+<table class="compat-table">
+ <tbody>
+ <tr>
+ <th>Feature</th>
+ <th>Chrome</th>
+ <th>Edge</th>
+ <th>Firefox (Gecko)</th>
+ <th>Internet Explorer</th>
+ <th>Opera</th>
+ <th>Safari</th>
+ </tr>
+ <tr>
+ <td>Basic support</td>
+ <td>{{CompatVersionUnknown}}</td>
+ <td>13</td>
+ <td>{{CompatGeckoDesktop(26)}}</td>
+ <td>{{CompatNo}}</td>
+ <td>{{CompatVersionUnknown}}</td>
+ <td>{{CompatSafari(10)}}</td>
+ </tr>
+ </tbody>
+</table>
+</div>
+
+<div id="compat-mobile">
+<table class="compat-table">
+ <tbody>
+ <tr>
+ <th>Feature</th>
+ <th>Android</th>
+ <th>Chrome for Android</th>
+ <th>Firefox Mobile (Gecko)</th>
+ <th>IE Mobile</th>
+ <th>Opera Mobile</th>
+ <th>Safari Mobile</th>
+ </tr>
+ <tr>
+ <td>Basic support</td>
+ <td>5.1</td>
+ <td>{{CompatVersionUnknown}}</td>
+ <td>{{CompatGeckoMobile(26)}}</td>
+ <td>{{CompatUnknown}}</td>
+ <td>{{CompatUnknown}}</td>
+ <td>10</td>
+ </tr>
+ </tbody>
+</table>
+</div>
+
+<h2 id="Смотрите_также">Смотрите также</h2>
+
+<ul>
+ <li><code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/function*">function*</a></code></li>
+</ul>