請問這個python代碼在javascript中的等價物是什么
guessed_index = [
i for i, letter in enumerate(self.chosen_word)
if letter == self.guess
]
ES6 中不存在列舉和串列理解,我如何將這兩個想法合二為一
uj5u.com熱心網友回復:
關注問題的可迭代/enumerate部分,而不是您正在執行的特定任務:您可以使用生成器函式實作Python 的enumerateJavaScript 模擬,并通過(或手動)使用生成的生成器(它是可迭代的超集)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);
uj5u.com熱心網友回復:
也許findIndex有用?
const word = "Hello";
const guess = "o";
const guessed_index = [...word].findIndex(letter => letter === guess);
console.log(guessed_index)
uj5u.com熱心網友回復:
為了讓不精通 Python 的潛在讀者清楚起見,下面是與您的理解等效的 Python 回圈:
guessed_index = []
i = 0
for letter in self.chosen_word:
if letter == self.guess:
guessed_index.append(i)
i = 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/354100.html
標籤:javascript Python 列表理解 枚举
下一篇:單擊按鈕時將組件回傳到id
