for循环在Javascript中是如何工作的?我有几个Python代码片段,我想转换成JS在线运行,但总是会出现语法错误。
final_words = [i.split()[-1] for i in chosen_stimuli]
我将JS转换为
final_words = [i.split().slice(-1)[0] in chosen_stimuli]
我的第二个Python代码是
for word in final_words:
if word in ''.join(textbox.text).lower():
matched_words.append(word)
我把JS翻译成
for (word in final_words){
if word in ''.join(textbox.text).toLowerCase(){
matched_words.push(word)}
}
您不能仅仅通过随机添加括号和大括号将python转换为javascript。这是关于代码的实际概念。您的代码片段:
final_words = [i.split()[-1] for i in chosen_stimuli]
是使用列表理解将函数映射到列表上。因此,在js:中使用map
let final_words = chosen_stimuli.map(i => i.split(/s+/).slice(-1)[0]);
您的第二个代码:
for word in final_words:
if word in ''.join(textbox.text).lower():
matched_words.append(word)
在列表中循环,检查字符串是否包含单词,如果包含单词,则将其附加到数组中。所以,这样做:
for (let word of final_words) {
if (textbox.text.join("").toLowerCase().contains(word)) {
matched_words.push(word);
}
}
请注意,JS使用for...of
来循环遍历数组,而不是使用for...in
,后者的作用有所不同。