假設我想在單擊時為我的按鈕旋轉類名。單擊一次變成button-green,兩次button-yellow,三次button-red。然后它會重復,所以第四次點擊會button-green再次出現。
我知道其他技術如何做到這一點,我不是在尋求實施建議。我撰寫這個例子是為了理解 JavaScript 中的生成器。
這是我的生成器代碼:
function* rotator(items) {
while (true) {
for (const item of items) {
yield item;
}
}
}
const classRotator = rotator([
'button-green',
'button-yellow',
'button-red',
]);
document.getElementById('my-button').addEventListener('click', event => {
event.currentTarget.classList.add(classRotator.next().value);
});
它作業正常,除了它永遠不會擺脫以前的課程。最方便的方法是在獲取下一個狀態之前讀取當前狀態:
// .current is not a thing:
event.currentTarget.classList.remove(classRotator.current);
當然我可以自己保留這個值并使用它。同樣,我可以清除我rotator()自己使用的所有類。我什至可以讓我的生成器函式yield同時具有以前和當前的值:
function* rotator(items) {
let previous;
while (true) {
for (const item of items) {
yield {
item,
previous
};
previous = item;
}
}
}
然后像這樣使用它:
document.getElementById('my-button').addEventListener('click', event => {
const {item: className, previous: previousClassName} = classRotator.next().value;
event.currentTarget.classList.remove(previousClassName);
event.currentTarget.classList.add(className);
});
But that's not the point - for educational purpose I'm asking this question:
Can I read the current value of generator function in JavaScript? If not, is it to avoid using memory when it's not needed (this value can potentially be very big)?
uj5u.com熱心網友回復:
我可以在 JavaScript 中讀取生成器函式的當前值嗎?
不。
但是,如果您愿意,您可以輕松地自己實作。
如果不是,是為了避免在不需要時使用記憶體嗎?
也許。迭代器不應該粘在它生成的最后一個值上,以允許獨立的垃圾收集并降低保留耗盡或尚未完成的生成器的成本。
但我認為.current設計中沒有可用欄位的主要原因是從理論的角度來看它沒有意義:在迭代開始之前或迭代器耗盡之后,該欄位具有什么價值?可以選擇undefined,但簡潔的設計根本沒有該欄位,并且只有在您實際執行迭代器時才回傳值。
uj5u.com熱心網友回復:
JavaScript“本機”API 通常愿意瘋狂地創建新物件。從表面上看,保存記憶通常不是語言委員會的基本目標。
創建一個通用工具將呼叫生成器的結果包裝在一個物件中,該物件將.next()方法委托給實際結果物件,但也將每個回傳值保存為一個.current()值(或任何適用于您的應用程式的值)將是非常簡單的。有一個.current() 是有用的,用于上述目的的詞法分析器的編程語言。然而,基本的生成器 API 并沒有為此做準備。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/350999.html
上一篇:Node.js緩沖區在類中未定義
