为什么第二个 for 循环需要 +i

Why does the second for loop need +i?

本文关键字:循环 第二个 for 为什么      更新时间:2023-09-26

我了解所有这些以及它是如何工作的,除了:为什么第二个 for 循环需要"+i"?为什么不能用"+1"代替?

text = "Blah blah blah blah blah blah Eric
blah blah blah Eric blah blah Eric blah blah
blah blah blah blah blah Eric";
var myName = "Eric";
var hits = [];
// Look for "E" in the text
for(var i = 0; i < text.length; i++) {
    if (text[i] === "E") {
        // If we find it, add characters up to
        // the length of my name to the array
        for(var j = i; j < (myName.length + i); j++) {
            hits.push(text[j]);
        }
    }
}
if (hits.length === 0) {
    console.log("Your name wasn't found!");
} else {
    console.log(hits);
}

j 循环偏移 i

i从0到text.length,比如说,从0到100。

每当找到一个"E"时,ji循环到i + myName.length,例如从50到54。

您还可以j从 0 到 myName.length 循环并执行text[j + i] .


请注意,此代码实际上并不查找"Eric",它查找一个"E",然后记录接下来的 4 个字符。如果输入字符串"EaEbEc foo"则结果将[ "EaEb", "EbEc", "Ec f" ]

它之所以做 + i,是因为代码试图将 Eric 的每一次出现从文本推送到 Hits,所以它想要计算 myname.length 字母。这也可以通过 j 从 0 开始并使用 text[j + i] 来实现

i 等于文本中的当前位置。例如

     v (i = 5 Starting from 0)
Blah Blah Blah

          v (i = 6)
Blah Blah Eric Blah

所以 i+name.length 是标记单词的结尾

          v->v (i=11 -> i+lenth=14)
Blah Blah Eric Blah

如果你拿+1,你会得到

 v<-------v (i=11 -> 1)
Blah Blah Eric Blah