我怎样搜索我的名字?(JavaScript)

How can I search for my name? (JavaScript)

本文关键字:JavaScript 我的名字 搜索      更新时间:2023-09-26

我想创建一个基本的搜索"引擎"。这是我的代码,但它不起作用:

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);    
    }   
}

我知道这很可怕,但我喜欢尝试PS:我学JavaScript还不到5天

如果你想在你的名字中找到一些文本,那么你可以使用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
   } 
}

我不确定任务是什么,但这里有一个简单的程序。你可以在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)")

这是一个有效的例子,我不喜欢警告和提示,但它可以告诉你应该往哪个方向走。这只是一个快速简单的例子,我建议你花时间分析你的需求和学习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');
}

我希望您能够快速地跳过代码中警告的可怕使用:)