Μετάβαση στο κύριο περιεχόμενο
← ⚡ JavaScript & the browser·Ενότητα C6 · Μάθημα 6
ΕργασίαDefine function* odds() yielding 1,3,5 and function* evens() yielding 2,4,6. Use yield* in function* both() to concatenate them. Then write function* walk(node) yielding node.value then walking each child recursively. Log [...both()].join(',') and [...walk({value:'a',children:[{value:'b',children:[{value:'c'}]}]})].join('>').

yield* — delegating to another iterable

125 XP8 min
Θεωρία

What yield* does

yield* otherIterable yields every value from another iterable in place. Same effect as a manual for-of with yield, but built into the syntax.

function* head() { yield 1; yield 2; }
function* tail() { yield 3; yield 4; }

function* both() {
  yield* head();
  yield* tail();
}

console.log([...both()]); // [1, 2, 3, 4]

Recursion

yield* recurses naturally. A tree walker in five lines:

function* walk(node) {
  yield node.value;
  for (const child of node.children ?? []) {
    yield* walk(child);
  }
}

A flat for-of walk(root) traverses the whole tree depth-first. No manual stack, no helper class.

Versus calling .next() in a loop

yield* x correctly forwards return values, .throw(), and stops when the inner iterable is done. The manual version is bug-prone — every helper file has a story about doing it manually and getting it wrong.

🔒

Εγγράψου για να αρχίσεις να προγραμματίζεις

Η θεωρία είναι ανοιχτή για όλους. Ο επεξεργαστής, η ζωντανή προεπισκόπηση και ο έλεγχος ξεκλειδώνουν με 7-ήμερη δωρεάν δοκιμή — απαιτείται κάρτα.

Εγγραφή — δωρεάν δοκιμή →

Τα πρώτα 10 μαθήματα κάθε διαδρομής είναι δωρεάν. Δεν χρειάζεται κάρτα.

← ΠροηγούμενοΕπόμενο μάθημα →

Μια συμβουλή Python ή web την ημέρα — με email

Σύντομο, γραμμένο στο χέρι, χωρίς spam. Διαγραφή με ένα κλικ.