请问这段python代码的javascript中的等价物是什么?
guessed_index = [
i for i, letter in enumerate(self.chosen_word)
if letter == self.guess
]枚举和列表理解在ES6等效项中都不存在,如何将这两个概念合并为一个
发布于 2021-11-09 15:26:37
专注于问题的可迭代/enumerate部分,而不是正在执行的特定任务:您可以使用generator function实现Python's enumerate的JavaScript模拟,并通过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);
发布于 2021-11-09 15:25:16
也许findIndex是有用的?
const word = "Hello";
const guess = "o";
const guessed_index = [...word].findIndex(letter => letter === guess);
console.log(guessed_index)
发布于 2021-11-09 15:26:44
对于不精通python的潜在读者来说,为了清楚起见,下面是与您的理解相当的python循环:
guessed_index = []
i = 0
for letter in self.chosen_word:
if letter == self.guess:
guessed_index.append(i)
i += 1https://stackoverflow.com/questions/69900694
复制相似问题