简体   繁体   English

使用for循环的多个条件

[英]Multiple conditions using for loop

I'm beginning programming with codecademy and I tried to write a "search for word" program, but I don't know how to write a condition in if using a for loop to check all the letters in a search word, no matter the length. 我开始与Codecademy网站编程,我试图写一个“搜索词”计划,但我不知道怎么写了条件if使用for循环来检查所有的字母在检索词,无论是长度。

I know the for loop gives me true or false , but I would like it to generate as many text[j] === myWord[ji] conditions to my code as there are letters. 我知道for循环让我truefalse ,但我想它产生尽可能多的text[j] === myWord[ji]条件,我的代码,因为有字母。

Is there something wrong with my syntax or should I use other command that I don't know of? 我的语法有问题吗?还是应该使用我不知道的其他命令?

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

You should move the if condition inside the inner loop like below 您应该将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]);
        }       
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM