2015-08-14 16 views
-2

我想創建一個基本的搜索「引擎」。這裏是我的代碼,但它不工作:如何搜索我的名字? (JavaScript)

alert("Search for your name!"); 

var name = prompt("Type in your name.").toLowerCase().split(""); 

var text = prompt("Type in some text with your name in it.").toLowerCase().split(""); 

var arrayNumber = 0; 

var hits = []; 

for(var i = 0; i < text.length; i++) { 

    if(name !== hits){ 

     if(text[i] === name[arrayNumber]) { 

       hits.push(text[i]); 
       arrayNumber = arrayNumber + 1; 

     } else if (text[i] !== name[arrayNumber]) { 
      hits = []; 
      arrayNumber = 0; 
     } else { 
      alert("Soemthing went wrong!"); 
     } 
    } else { 
     alert(hits);  
    } 
} 

我敢肯定,這是可怕的,但我想嘗試:d PS:我一直在學習JavaScript不到5天。

+0

想象一下你的車機械師。 「這是我的車,它不起作用,再見!」你認爲他會很開心嗎? –

+0

基本上,我想在特定的文本中找到名稱並提醒它。 –

回答

0

如果你想在你的名字中找到一些文字,那麼你可以使用indexof。

function Search() 
{ 
alert("Search for your name!"); 

var name = prompt("Type in your name.").toLowerCase().split(""); 

var text = prompt("Type in some text with your name in it.").toLowerCase().split(""); 
    if(name.indexof(text) > 0) 
    { 
    /// here your logic 
    } 
} 
0

我不確定是什麼任務,但這裏是一個簡單的程序。你可以嘗試在的jsfiddle

alert("Search for your name!"); 

var name = prompt("Type in your name.").toLowerCase(); 
console.log(name); 

var text = prompt("Type in some text with your name in it.").toLowerCase().split(" "); 
console.log(text); 

var arrayNumber = 0; 

var hits = 0; 

for(var i = 0; i < text.length; i++) { 
    if(name === text[i]) 
     hits++; 
} 

if(hits === 0) 
    alert("Your name is not found!") 
else 
    alert("Found your name " + hits + " time(s)") 
0

這裏是工作的例子,我不喜歡警報和提示,但它可以告訴你你應該去什麼方向。 這只是一個簡單的例子,我建議您花時間分析您的需求並學習OOP JS,以便您的簡單搜索的最終結構可以維護。

alert("Search for your name!"); 
 

 
var name = prompt("Type in your name.").toLowerCase().split(" "); 
 
var text = prompt("Type in some text with your name in it.").toLowerCase(); 
 
var hits = 0; 
 

 
for(var i = 0; i < name.length; i++) { 
 

 
    if(text.indexOf(name[i]) > -1) { 
 
     hits++; 
 
    } 
 

 
} 
 

 
if(hits == name.length) { 
 
    alert('full match'); 
 
} 
 
else if(hits > 0 && name.length > 1) { 
 
    alert('partial match'); 
 
} 
 
else { 
 
    alert('no matches'); 
 
}

我希望你能夠快速晃過警報可怕的使用在你的代碼:)