您好,我目前正在Code Academy进行javascript课程,其中包括" for"环路。
但是这个练习对我来说没有意义,如果没有理解为什么我正在做我正在做的事情那就没有意义了......这里有代码。
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);
}
我得到第一个循环,但令我困惑的是if语句中的整个第二个循环....
for(var j = i; j < (myName.length + i); j++) {
hits.push(text[j]);
}
只是不明白我在做什么?
答案 0 :(得分:1)
第二个循环是循环,基本上是将你名字的其余字母添加到数组
中j = i - &gt;这意味着它将从i的位置开始,这是它发现了一个&#34; E&#34;在你的情况下
j&lt; (myname.length + i) - &gt;取你的名字+ i的长度,这将给你的位置直到你的名字结束
j ++ - &gt;这是将j增加1
hits.push(text [j]) - &gt;这将根据j索引
将下一个字母推送到hits数组所以基本上,内部循环从你名字的第一个字母开始,然后运行你的名字的长度,将字符串中的其余字母添加到命中数组,最后添加你的名字的字母进入数组
你最终会看到这样的阵列 命中= {E,r,i,c,E,r,i,c,E,r,i,c}
答案 1 :(得分:1)
它从索引开始一个新循环,其中在初始文本中找到字符E
,直到myName.length + i
索引,该索引基本上循环遍历myName
描述的子字符串。对于该循环的每次迭代,它将当前迭代的字符添加到hits
。
请注意,代码会推断以E
开头的所有内容都等于yourName
,这非常幼稚。
为什么myName.length + i
?
aaaaEric
。E
,所以i = 4
。Eric
。i
,则最终会得到j = 4; j < 4; j++
,而这将不会循环播放。您必须将(i
)的位置添加到结束条件,这将给出j = 4; j < 8; j++
并正确循环Eric
,然后返回主循环。在这种情况下,最后hits
应该看起来像['E','r','i','c','E','r','i','c','E','r','i','c']
。
答案 2 :(得分:0)
&#34;练习&#34;是后精制物质的蒸汽负荷。这是一个固定的练习&#34;应该有希望更有意义,完整的内联解释。 (如果理解这一点,&#34;示例&#34;废话至少应该更清楚一点。)
var text = "Blah blah ELEPHANT blah blah blah Eric \
blah blah blah Eric blah blah Eric blah blah \
blah blah blah EGRET blah Eric";
var name = "Eric";
var foundAt = [];
// Loop through the text one character at a time over the
// indices [0, text.length), incrementing i by at the end of each loop.
for(var i = 0; i < text.length; i++) {
// And for every index in the text, start to loop over the indices in
// our name, or from [0, name.length). Once again, the increment to
// j happens at the end of each loop.
for (var j = 0; j < name.length; j++) {
// Look at where we currently are in the text, and compare the
// character where we are currently looking in our name.
// (Note that we look at character i+j into the text, because we
// look 0+j into the name.)
if (text[i + j] == name[j]) {
// Yup, still matches our name!
if (j == name.length - 1) {
// The last character matched too. This must be our name, or
// our name was found as part of a longer word.
// Let's record the index in the text where our name started!
foundAt.push(i);
}
} else {
// Did not match our name, so we stop looking through the rest
// of the name and continue looking through the next character
// in the text (this terminates the inner loop early).
break;
}
}
}
if (foundAt.length) {
// \o/ Hooray!! \o/
// We found our name at least once, show where it was found.
console.log(foundAt);
} else {
console.log("Nope, nothing here");
}
And a fiddle。尝试更改名称。