diff options
| author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:52 -0500 |
|---|---|---|
| committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:52 -0500 |
| commit | 074785cea106179cb3305637055ab0a009ca74f2 (patch) | |
| tree | e6ae371cccd642aa2b67f39752a2cdf1fd4eb040 /files/ru/web/javascript/reference/operators/yield_star_ | |
| parent | da78a9e329e272dedb2400b79a3bdeebff387d47 (diff) | |
| download | translated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.gz translated-content-074785cea106179cb3305637055ab0a009ca74f2.tar.bz2 translated-content-074785cea106179cb3305637055ab0a009ca74f2.zip | |
initial commit
Diffstat (limited to 'files/ru/web/javascript/reference/operators/yield_star_')
| -rw-r--r-- | files/ru/web/javascript/reference/operators/yield_star_/index.html | 227 |
1 files changed, 227 insertions, 0 deletions
diff --git a/files/ru/web/javascript/reference/operators/yield_star_/index.html b/files/ru/web/javascript/reference/operators/yield_star_/index.html new file mode 100644 index 0000000000..c20f6969e6 --- /dev/null +++ b/files/ru/web/javascript/reference/operators/yield_star_/index.html @@ -0,0 +1,227 @@ +--- +title: yield* +slug: Web/JavaScript/Reference/Operators/yield* +translation_of: Web/JavaScript/Reference/Operators/yield* +--- +<div>{{jsSidebar("Operators")}}</div> + +<p><strong>Выражение <code>yield*</code> </strong>используется для того, чтобы "передать упраевление" функцией-генератором другому {{jsxref("Statements/function*", "генератору")}} или итерируемому объекту.</p> + +<h2 id="Синтаксис">Синтаксис</h2> + +<pre class="syntaxbox notranslate"> yield* [[expression]];</pre> + +<dl> + <dt><code>expression</code></dt> + <dd>Итерируемый объект</dd> +</dl> + +<h2 id="Описание">Описание</h2> + +<p>Выражение <code>yield*</code> в функции-генераторе принимает итерируемый объект и возвращает его значения по очереди, как если бы эта функция-генератор возвращала иъ сама.</p> + +<p>Значение выражения <code>yield*</code> само по себе равно посленему значению итурируемого объекта (т.е., того когда <code>done</code> равно true).</p> + +<h2 id="Примеры">Примеры</h2> + +<h3 id="Передача_другому_генератору">Передача другому генератору</h3> + +<p>В следующем примере, значения полученные из <code>g1()</code> возвращаются из <code>g2</code> вызовами <code>next</code>, как будто бы она вычислила их сама.</p> + +<pre class="brush: js notranslate">function* g1() { + yield 2; + yield 3; + yield 4; +} + +function* g2() { + yield 1; + yield* g1(); + yield 5; +} + +var iterator = g2(); + +console.log(iterator.next()); // { value: 1, done: false } +console.log(iterator.next()); // { value: 2, done: false } +console.log(iterator.next()); // { value: 3, done: false } +console.log(iterator.next()); // { value: 4, done: false } +console.log(iterator.next()); // { value: 5, done: false } +console.log(iterator.next()); // { value: undefined, done: true } +</pre> + +<h3 id="Другие_итерируемые_объекты">Другие итерируемые объекты</h3> + +<p>Помимо объектов генераторов, <code>yield*</code> может перебирать другие виды итерируемых объектов, т.е. массивы, строки, объекты аргументов и др.</p> + +<pre class="brush: js notranslate">function* g3() { + yield* [1, 2]; + yield* "34"; + yield* Array.from(arguments); + // Определение этого итератора ниже + yield* new PowesOfTwo(4) +} + +var iterator = g3(5, 6); + +// Значения из массива +console.log(iterator.next()); // { value: 1, done: false } +console.log(iterator.next()); // { value: 2, done: false } +// Из строки +console.log(iterator.next()); // { value: "3", done: false } +console.log(iterator.next()); // { value: "4", done: false } +// Из аргументов +console.log(iterator.next()); // { value: 5, done: false } +console.log(iterator.next()); // { value: 6, done: false } +// Из специального итератора +console.log(iterator.next()); // { value: 1, done: false } +console.log(iterator.next()); // { value: 2, done: false } +console.log(iterator.next()); // { value: 4, done: false } + +console.log(iterator.next()); // { value: undefined, done: true } + +// Итератор, который возвращает все степени двойки +// до maximum включительно +class PowersOfTwo { + constructor(maximum) { + this.maximum = maximum + this.value = 1 + } + [Symbol.iterator]() { + const self = this + return { + next() { + if(self.value > self.maximum) return { done: true } + + const value = self.value + self.value *= 2 + return { done: false, value } + } + } + } +} +</pre> + +<h3 id="Собственное_значение_выражения_yield*">Собственное значение выражения <code>yield*</code></h3> + +<p><code>yield*</code> - это выражение, а не оператор, поэтому оно имеет значение, равное последнему значению итератора </p> + +<pre class="brush: js notranslate">function* g4() { + yield* [1, 2, 3]; + return "foo"; +} + +var result; + +function* g5() { + result = yield* g4(); +} + +var iterator = g5(); + +console.log(iterator.next()); // { value: 1, done: false } +console.log(iterator.next()); // { value: 2, done: false } +console.log(iterator.next()); // { value: 3, done: false } +console.log(iterator.next()); // { value: undefined, done: true }, + // g4() в этой точке вернёт { value: "foo", done: true } + +console.log(result); // "foo" +</pre> + +<h2 id="Спецификации">Спецификации</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ES6', '#', 'Yield')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#', 'Yield')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="Поддержка_браузерами">Поддержка браузерами</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 (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("27.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>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>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoMobile("27.0")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="Специфичные_для_Firefox_примечания">Специфичные для Firefox примечания</h2> + +<ul> + <li>Начиная с Gecko 33 {{geckoRelease(33)}}, разбор выражений yield было приведено к соответствию с последними спецификациями ES6 ({{bug(981599)}}): + <ul> + <li>Реализована корректная обработка разрыва строки. Разрыва строки между "yield" и "*" быть не может. Такой код вызовет {{jsxref("SyntaxError")}}: + <pre class="brush: js notranslate">function* foo() { + yield + *[]; +}</pre> + </li> + </ul> + </li> +</ul> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Guide/The_Iterator_protocol">The Iterator protocol</a></li> + <li>{{jsxref("Statements/function*", "function*")}}</li> + <li>{{jsxref("Operators/function*", "function* expression")}}</li> + <li>{{jsxref("Operators/yield", "yield")}}</li> +</ul> |
