function* 선언은 생성기 함수를 정의하는 데 사용됩니다. Generator 객체를 반환합니다. 생성기 함수를 사용하면 함수가 종료되고 나중에 다시 시작될 때 사이에 코드를 실행할 수 있습니다. 따라서 생성기를 사용하여 코드에서 흐름 제어를 관리할 수 있습니다.
구문
구문은 다음과 같습니다 -
function *myFunction() {}
// or
function* myFunction() {}
// or
function*myFunction() {} 제너레이터 함수를 사용하는 방법을 살펴보겠습니다.
예시
라이브 데모
<html>
<body>
<script>
function* display() {
var num = 1;
while (num < 5)
yield num++;
}
var myGenerator = display();
document.write(myGenerator.next().value);
document.write("<br>"+myGenerator.next().value);
document.write("<br>"+myGenerator.next().value);
document.write("<br>"+myGenerator.next().value);
document.write("<br>"+myGenerator.next().value);
</script>
</body>
</html>