繁体   English   中英

在javascript中包含枚举等效项的列表理解

[英]list comprehension containing enumerate equivalent in javascript

请问这个python代码在javascript中的等价物是什么

guessed_index = [
        i for i, letter in enumerate(self.chosen_word)
        if letter == self.guess
    ]

ES6 中不存在枚举和列表理解,我如何将这两个想法合二为一

也许findIndex有用?

 const word = "Hello"; const guess = "o"; const guessed_index = [...word].findIndex(letter => letter === guess); console.log(guessed_index)

关注问题的可迭代/ enumerate部分,而不是您正在执行的特定任务:您可以使用生成器函数实现Python enumerate的 JavaScript 模拟,并通过for-of使用生成的生成器(它是可迭代的超集) for-of (或手动,如果您愿意):

 function* enumerate(it, start = 0) { let index = start; for (const value of it) { yield [value, index++]; } } const word = "hello"; const guess = "l"; const guessed_indexes = []; for (const [value, index] of enumerate(word)) { if (value === guess) { guessed_indexes.push(index); } } console.log(`guessed_indexes for '${guess}' in '${word}':`, guessed_indexes);

或者您可以编写一个特定的生成器函数来执行查找匹配项的任务:

 function* matchingIndexes(word, guess) { let index = 0; for (const letter of word) { if (letter === guess) { yield index; } ++index; } } const word = "hello"; const guess = "l"; const guessed_indexes = [...matchingIndexes(word, guess)]; console.log(`guessed_indexes for '${guess}' in '${word}':`, guessed_indexes);

为了让不精通 Python 的潜在读者清楚起见,下面是与您的理解等效的 Python 循环:

guessed_index = []
i = 0
for letter in self.chosen_word:
    if letter == self.guess:
        guessed_index.append(i)
    i += 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM