嗨,我目前正在 Code Academy 上学习 javascript 类(class)。与“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]);
}
只是不明白我在做什么?
最佳答案
第二个循环基本上是将您名字的其余字母添加到数组中
j = i --> 这意味着它将从 i 的位置开始,这是在您的情况下找到“E”的位置
j < (myname.length + i) --> 正在获取您的姓名 + i 的长度,这将为您提供直到您姓名末尾的位置
j++ --> 这是将 j 加 1
hits.push(text[j]) --> 这将根据 j 索引将下一个字母推送到命中数组
所以基本上,内部循环从你名字的第一个字母开始,然后运行你名字的长度,将字符串中的其余字母添加到命中数组中,最终添加你名字的字母进入数组
你最终会得到这样的数组 点击数 = {E,r,i,c,E,r,i,c,E,r,i,c}
关于javascript - 试图理解javascript中的for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25325824/