使用for循环的多个条件

时间:2015-07-31 08:48:12

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

我开始使用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);
}

1 个答案:

答案 0 :(得分:0)

您应该在内部循环中移动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]);
        }       
    }
}