我有麻烦搞清楚我的JavaScript学习课程的条件。For循环条件问题
我没有得到正常的错误,因为我在使用过程中这样做,但我在使用过程中接收到错误是这样的......
Oops, try again. Careful: your second 'for' loop should stop when it reaches its current point in the string + myName.length.
这些都说明:
First, you'll want to set your second loop's iterator to start at the first one, so it picks up where that one left off. If your first loop starts with
for(var i = 0; // rest of loop setup
your second should be something like
for(var j = i; // rest of loop setup
Second, think hard about when your loop should stop. Check the Hint if you get stuck!
Finally, in the body of your loop, have your program use the .push() method of hits. Just like strings and arrays have a .length method, arrays have a .push() method that adds the thing between parentheses to the end of the array. For example,
newArray = [];
newArray.push('hello');
newArray[0]; // equals 'hello'
这是我的代码
var text = "Hello, my name is Becky. What is your name?\
I repeat, my name is Becky. Can't you figure out that my\
name is Becky. Becky!!!!";
var myName = "Becky";
var hits = [];
for (i = 0; i < text.length; i++) {
if (text[i] === 'B') {
for (var j = i; i < myName.length; i++) {
hits.push();
}
}
}
我知道问题在于这一行:
for (var j = i; i < myName.length; i++) {
我只是无法弄清楚到底我需要构造它。
UPDATE:问题
最终的答案:
/*jshint multistr:true */
var text = "Hello, my name is Becky. What is your name?\
I repeat, my name is Becky. Can't you figure out that my\
name is Becky. Becky!!!!";
var myName = "Becky";
var hits = [];
for (i = 0; i < text.length; i++) {
if (text[i] === 'B') {
for (var j = i; j < (i + myName.length); j++) {
hits.push(myName);
}
}
}
if (hits === 0) {
console.log("Your name wasn't found!");
} else {
console.log(hits);
}
的关键是在评论这一部分:“在字符串中... **当前点** + myName.length ......” –
那么'var j'?喜欢这个 '; j
Becky
首先分析一个for循环的结构:你有初始化,结束条件和增量。确定你的增量影响结束条件。 – dsh