我有麻煩搞清楚我的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