包含 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's enumerate
using a generator function 的 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);
为了不精通 python 的潜在读者清楚起见,下面是相当于您的理解的 python 循环:
guessed_index = []
i = 0
for letter in self.chosen_word:
if letter == self.guess:
guessed_index.append(i)
i += 1
请问这个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's enumerate
using a generator function 的 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);
为了不精通 python 的潜在读者清楚起见,下面是相当于您的理解的 python 循环:
guessed_index = []
i = 0
for letter in self.chosen_word:
if letter == self.guess:
guessed_index.append(i)
i += 1