Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

Generator Functions ใน JavaScript คืออะไร

Generators

JavaScript รองรับ Generator functions และ Generator Objects Generator function คล้ายฟังก์ชันทั่วไป แต่ใช้ keyword yield แทน return เมื่อต้องสร้างค่า yield หยุดการทำงานส่งค่ากลับ caller สามารถ resume จากจุดที่หยุดได้

รูปแบบ

function* generator(){ 
    yield 1; 
    yield 2; 
}

ตัวอย่าง

ใช้ generator function พิมพ์เลขธรรมชาติ 10, 9, 8 แทนที่จะพิมพ์ทีละตัว ใช้ for loop พิมพ์จำนวนที่ต้องการ

<html> <body> <script> 
    function* number() { 
        var num = 10; 
        while (true) { 
            yield num--; 
        } 
    } 
    var gen = number(); 
    document.write(gen.next().value); 
    document.write("<br>"); 
    document.write(gen.next().value); 
    document.write("<br>"); 
    document.write(gen.next().value); 
</script> </body> </html>

ผลลัพธ์

10 9 8