簡體   English   中英

Javascript 中的 Python itertools 循環等效項是什么?

[英]What is the Python itertools cycle equivalent in Javascript?

我在 itertools 中找不到 Python 循環的等效 function 循環:

from itertools import cycle
g = cycle(('a','b'))
next(g) # a
next(g) # b
next(g) # a
# etc. etc.

在 Javascript 中。

目標是在一組值中創建一個無限循環。 我想我可以使用 Javascript 生成器,但我想知道是否有任何內置的 function。

沒有內置功能。 話雖如此,很容易制作一個接受任意數量的 arguments 並循環遍歷它們的 function:

 function* cycle(...items) { while(true) yield* items; } const gen = cycle("a", "b"); console.log(gen.next().value); console.log(gen.next().value); console.log(gen.next().value);

這使用yield*委托給數組items的迭代器,有效地yield* items; 是一個較短的版本

for (const item of items)
  yield item;

或者,它可以接受一個數組並不斷循環其內容

 function* cycle(items) { while(true) yield* items; } const gen = cycle(["a", "b"]); console.log(gen.next().value); console.log(gen.next().value); console.log(gen.next().value);

如果它必須支持傳入的任何迭代,它必須維護第一次迭代的 chache,以便它可以重復進一步的循環。 我已經在我的這個答案中展示了這個實現。 這是實現:

 function* repeat(iterable) { const cache = []; //lazily supply the values from the iterable while caching them for (const next of iterable) { cache.push(next); yield next; } //delegate to the cache at this point while(true) yield* cache; } const newMap = new Map([ ['key1', 'value1'], ['key2', 'value2'] ]); const iterator = repeat(newMap.values()) // It can be newMap.entries() console.log(iterator.next().value) // prints value1 console.log(iterator.next().value) // prints value2 console.log(iterator.next().value) // prints value1 console.log(iterator.next().value) // prints value2 console.log(iterator.next().value) // prints value1 console.log(iterator.next().value) // prints value2


有一個名為Iterator helpers的提議,旨在添加類似於 itertools 的工具,並且通常簡化迭代器的使用。 該提案目前處於批准過程中的第 4 階段中的第 2 階段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM