Javascript 使用发电机功能的输入和输出

Javascript 使用发电机功能的输入和输出,javascript,caching,generator,Javascript,Caching,Generator,我正在试验使用generator函数,我想出了以下生成器。它是有效的,但我不明白它是如何使用收益率输入、处理它并使用相同的收益率语句来输出结果的 程序流程是如何工作的 //我的缓存生成器 函数*cache(){ 让输入、输出、缓存={}; while(true){ 投入=产出; //一些代码。。。 if(缓存中的输入){ 输出=缓存[输入]; console.log(“旧值:”+输出); }否则{ 输出=f(输入); 缓存[输入]=输出; console.log(“新值:”+输出); } }

我正在试验使用generator函数,我想出了以下生成器。它是有效的,但我不明白它是如何使用收益率输入、处理它并使用相同的收益率语句来输出结果的

程序流程是如何工作的

//我的缓存生成器
函数*cache(){
让输入、输出、缓存={};
while(true){
投入=产出;
//一些代码。。。
if(缓存中的输入){
输出=缓存[输入];
console.log(“旧值:”+输出);
}否则{
输出=f(输入);
缓存[输入]=输出;
console.log(“新值:”+输出);
}
}
}
//一些昂贵的功能:
函数f(x){
返回x.split(“”).reverse().join(“”);
}
常数c=cache();
console.log(“返回值:+c.next(“这已丢失”).value);
log(“返回值:”+c.next(“Hello”).value);
console.log(“返回值:”+c.next(“World”).value);
log(“返回值:”+c.next(“Hello”).value);
console.log(“返回值:”+c.next(“Stackoverflow”).value)我将尝试一下:

const c = cache();
console.log("Return value: "+ c.next("this is lost").value);
这为
c
分配了一个迭代器函数,用于
cache
(第一行),然后最初运行
cache
,直到第一个
生成表达式,因此基本上该代码:

let input, output, cache = {};
yield output;
output
undefined
,因此从第一次
next()
调用返回
undefined
。但是请注意,参数(
“this is lost”
)未传递到此
中。它将被传递到
yield
中,在那里先前的执行被暂停。因为之前没有运行过
c.next
,所以它确实丢失了

在下一次运行中:

console.log("Return value: "+ c.next("Hello").value);
执行以下代码:

input = "Hello"; // the yield is substituted with the next() argument here!
//Some code...
if(input in cache){ // false
  output = cache[input];
  console.log("Old Value: "+output);
} else {
  output = f(input);
  cache[input] = output;
  console.log("New Value: "+output);
}
yield output // "olleH"
函数在它之前停止的那一行恢复,并且
yield output
被替换为
next()
参数。说:

使用参数调用next()方法将恢复生成器函数的执行,并使用next()中的参数替换暂停执行的产量表达式


你读过吗?你能更具体地说明一下你在当前代码中不理解的地方吗?是的,我读过。我希望c.next()返回上一次输入的结果,因为这就是那个值,输出保持不变…我不明白你说的是什么,抱歉