【问题标题】:Multiple conditions using for loop使用 for 循环的多个条件
【发布时间】:2015-10-22 21:08:28
【问题描述】:

我开始使用 codecademy 进行编程,并尝试编写“搜索单词”程序,但我不知道如何在 if 中编写条件,使用 for 循环检查所有字母一个搜索词,无论长度如何。

我知道 for 循环给了我truefalse,但我希望它为我的代码生成与字母一样多的text[j] === myWord[j-i] 条件。

我的语法有问题还是应该使用其他我不知道的命令?

var text = "Within the field of literary criticism, text also refers to the original information content of a particular piece of writing; that is, the text of a work is that primal symbolic arrangement of letters as originally composed, apart from later alterations, deterioration, commentary, translations, paratext, etc. Therefore, when literary criticism is concerned with the determination of a text, it is concerned with the distinguishing of the original information content from whatever has been added to or subtracted from that content as it appears in a given textual document (that is, a physical representation of text).";

var myWord = "literary";
var hits = [];

for (var i=0; i < text.length; i++) {
    if (for (var j=i; j<(i + myWord.length); j++){
            text[j]===myWord[j-i]
        })
        hits.push(text[i])
    }
}

if (hits.length === 0) {
    console.log("Your name wasn't found!");
}
else {
    console.log(hits);
}

【问题讨论】:

    标签: javascript if-statement for-loop conditional-statements


    【解决方案1】:

    您应该将if 条件移动到内部循环中,如下所示

    for (var i = 0; i < text.length; i++) {
        for (var j = i; j < (i + myWord.length); j++){
                if(text[j]===myWord[j-i])
                    hits.push(text[i]);
            }       
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-09-02
      • 1970-01-01
      • 1970-01-01
      • 2013-05-27
      • 2013-01-27
      • 2012-08-04
      • 2023-01-29
      • 2018-06-26
      相关资源
      最近更新 更多