| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/ru/docs/Web/JavaScript/Guide/Iterators_and_generators | [Back] [Original] |
Get to know MDN better
This page was translated from English by the community. Learn more and join the MDN Web Docs community.
. JavaScript , for map(), filter() array comprehensions. for...of .
. :
, , . JavaScript - , next(), . : done value.
, - , next().
function makeIterator(array) {
var nextIndex = 0;
return {
next: function () {
return nextIndex < array.length
? { value: array[nextIndex++], done: false }
: { done: true };
},
};
}
, next() - :
var it = makeIterator(["yo", "ya"]);
console.log(it.next().value); // 'yo'
console.log(it.next().value); // 'ya'
console.log(it.next().done); // true
function* idMaker() {
var index = 0;
while (true) yield index++;
}
var it = idMaker();
console.log(it.next().value); // 0
console.log(it.next().value); // 1
console.log(it.next().value); // 2
// ...
, , , , for..of. , Array Map, , , , , Object, .
, @@iterator, , ( ) Symbol.iterator:
:
var myIterable = {};
myIterable[Symbol.iterator] = function* () {
yield 1;
yield 2;
yield 3;
};
[...myIterable]; // [1, 2, 3]
String, Array, TypedArray, Map Set , Symbol.iterator.
, , for-of , spread operator, yield*, destructuring assignment.
for (let value of ["a", "b", "c"]) {
console.log(value);
}
// "a"
// "b"
// "c"
[..."abc"]; // ["a", "b", "c"]
function* gen() {
yield* ["a", "b", "c"];
}
gen().next()[(a, b, c)] = // { value:"a", done:false }
new Set(["a", "b", "c"]);
a; // "a"
yield , , , .
next() , . , next(), yield , .
, next(x) :
function* fibonacci() {
var fn1 = 1;
var fn2 = 1;
while (true) {
var current = fn2;
fn2 = fn1;
fn1 = fn1 + current;
var reset = yield current;
if (reset) {
fn1 = 1;
fn2 = 1;
}
}
}
var sequence = fibonacci();
console.log(sequence.next().value); // 1
console.log(sequence.next().value); // 1
console.log(sequence.next().value); // 2
console.log(sequence.next().value); // 3
console.log(sequence.next().value); // 5
console.log(sequence.next().value); // 8
console.log(sequence.next().value); // 13
console.log(sequence.next(true).value); // 1
console.log(sequence.next().value); // 1
console.log(sequence.next().value); // 2
console.log(sequence.next().value); // 3
:
, next(undefined) next(). next() , undefined, TypeError.
, throw() , . , yield throw .
yield , throw(), next() done true.
This page was last modified on 29 . 2026 . by MDN contributors.
Your blueprint for a better internet.
Portions of this content are 19982026 by individual mozilla.org contributors. Content available under a Creative Commons license.
| Web Proxy Viewer | New URL | Original Page |