2017-02-28 42 views
-2

所以。開始數組。是和環路一樣好。結果,我需要幫助。陣列正在造成我的問題

/*jshint multistr:true */ 
    var text = "Yo yo yo, what's/good fam. My name is/Caleb, my dude."; 
    var myName = "Caleb" 
    var hits = [] 
    for(var i = 0; i >= text.length; i++){ 
     if(text[i] === 'C') { 
      } 
      for(var j = i; i <= i + myName.length; i++){ 
       } 
    } 

這是我的確切代碼。現在,它需要做的是在文本字符串的範圍內搜索我的名字。唯一的問題是,它說'看起來像你的第二'for'循環不會將值推向匹配數組。確保它正常工作,並且myName的文本出現在文本變量的某處。這 CodeAcademy項目。我只是不理解。如果有人能夠幫助我,我會很感激。

謝謝!

+0

搜索您的名字。好的。然後怎樣呢? – mehulmpt

+0

是的,你的代碼是不完整的。一旦你找到字母'C',你再次循環,但是這個循環沒有做任何事情。 'for(var j = i; i <= i + myName.length; i ++){addStuffToDoHere}'但是,如下所述,它也是無限的,所以這個循環需要改變。 – Shilly

+2

如果這是一個項目,我建議不要求答案。爲了引導你朝着正確的方向發展,我會建議.indexOf和.split函數 –

回答

0

首先確保你有正確的所有分號。此外,添加一些行動,以防止循環得到結果! 另外,我不認爲你已經定義了var j,是嗎?

最後 - 如果它要求u到一定值推入命中數組,然後用這個推法:

hits.push(); 

爲了幫助ü我需要的任務本身更深入的瞭解。你必須做什麼,你以什麼開始?

編輯:

var myName = "Caleb"; // define myName before text so it can be used in text 
var text = "Yo yo yo, what's/good fam. My name is/"+myName+", my dude."; // define text and use myName variable between two strings, connected with + 
var hits = []; // define hits array 
for(var i = 0; i < text.length; i++) { //start loop, make sure second parameter is not infinite or it would crash your browser 
     if(text[i] === 'C') { // if found i that corresponds with 'C' 
        var letterLocation = i; // set variable letterLocation with value of 'C' position 
       hits.push(i); // add the location number to hits array with .push method 
      }; 
    }; 
console.log(hits); // display hits array in console 

下面是一些對你的工作代碼,只需按照任務和改變一切必要 - 希望它幫助。 通常 - 我改變了變量的順序,這樣你就可以在文本中使用myName,也可以讓for循環打印出字母C的位置,並將這個值推送到匹配數組中。那是你的意思嗎?

+0

只是用解釋編輯了代碼,讓我知道它是否有任何用處 –