function* stopFun(){ let x = 1; console.log(1) yield x = x+1; console.log(2); } ------------------------------------ let it = stopFun(); console.log(it.next()); 控制檯打印以下: 1 {value:2,done:false} ------------------------------------ ------------------------------------ let it = stopFun(); console.log(it.next()); console.log(it.next()); 控制檯打印以下: 1 {value:2,done:false} 2 {value: undefined, done: true} ------------------------------------
總結:java
老驢拉新磨,磨轉豆產粉...函數
function* changeFun(a){ console.log(a); let b = yield (a+1); console.log(b); let c = b*2; console.log(c); } ------------------------------------ let it = changeFun(1); console.log(it.next()); console.log(it.next()); 控制檯打印以下: 1 {value: 2, done: false} undefined NaN {value: undefined, done: true} ------------------------------------ ------------------------------------ let it = changeFun(1); console.log(it.next()); console.log(it.next(2)); 控制檯打印以下: 1 {value: 2, done: false} 2 4 {value: undefined, done: true} ------------------------------------
總結code
若是這一局遊戲不想玩了,玩家是能夠直接return的,強制退出,注意:是強制退出,後面的都不用走了!對象
function* returnTest(){ console.log(1); yield x = "遊戲存檔"; console.log(2); return "game over!" } ------------------------------------ let it = returnTest(); console.log(it.next()); console.log(it.return()); console.log(it.next()); 控制檯打印以下: 1 {value: "遊戲存檔", done: false} {value: undefined, done: true} {value: undefined, done: true} ------------------------------------
function* recycleFun(){ yield a = "1"; yield "2"; yield "3"; yield "over"; } ------------------------------------ let it = recycleFun(); for(let value of it){ console.log(value) } 控制檯打印以下: 1 2 3 over ------------------------------------