循环语法错误的Javascript Python

2024-04-29 10:17:19 发布

您现在位置:Python中文网/ 问答频道 /正文

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)}
}

Tags: 代码textinforifjswordfinal
1条回答
网友
1楼 · 发布于 2024-04-29 10:17:19

您不能仅仅通过随机添加括号和大括号将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,这做了一些不同的事情

相关问题 更多 >