Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Biểu thức/Từ khóa yield* trong JavaScript


yield* (yield star) dùng để ủy thác (delegate) cho một generator hoặc iterable object khác. Nó lặp qua iterable đó và yield từng giá trị ra bên ngoài.

Ví dụ

<!DOCTYPE html> <html lang="vi"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>yield* keyword</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 20px; font-weight: 500; color: blueviolet; } </style> </head> <body> <h1>Từ khóa yield* trong JavaScript</h1> <div class="result"></div> <br /> <button class="Btn">NHẤN VÀO ĐÂY</button> <h3>Nhấn nút để lặp qua test2 và xem giá trị yield ra</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); function* test() { yield 12; yield 24; yield 36; } function* test2() { yield* test(); } let iterator = test2(); BtnEle.addEventListener("click", () => { resEle.innerHTML = iterator.next().value + "<br>"; resEle.innerHTML += iterator.next().value + "<br>"; resEle.innerHTML += iterator.next().value + "<br>"; }); </script> </body> </html>

Kết quả

Khi nhấn nút lần lượt hiển thị: 12, 24, 36.

yield* test() tương đương với:

for (const value of test()) { yield value; }

Cũng hoạt động với bất kỳ iterable nào: yield* [1,2,3], yield* new Set([...]), yield* "abc".