【问题标题】:How to fix this program so it searches only my name?如何修复这个程序,使它只搜索我的名字?
【发布时间】:2016-12-12 20:19:43
【问题描述】:

我正在学习 JavaScript 并且我构建了这个程序,它搜索 String 中的字母 E 的实例,然后将一个字母一个字母地存储到array,但现在当它找到字母 E 的类似实例时,它也会输出类似的实例,在这种情况下,我有 Eddie 和 Eric。而且我不希望它输出类似的实例,在这种情况下是 Eric。我知道有一种 hacky 方法可以做到这一点,例如 if(nameYouFound !== "myName")。但我不喜欢它......在我学到这一点的网站上,它说有内置的 JavaScript,string 方法可以提供帮助。你知道有什么方法可以解决问题吗?

请不要用 JQuery 回答,我正在努力变得更好 JavaScript...

这里是sn-p的代码:

/*jshint multistr:true */
var text, myName, hits, i, j;
text = "Hello, there, how are you feeling Eddie hope you are ok, ok Eric";
myName = "Eddie";
hits = [];
for (i = 0; i < text.length; i++) {
  if (text[i] === "E") {
    for (j = i; j < (myName.length + i); j++) {
      hits.push(text[j]);
    }
  }
}

if (hits.length == 0) {
  alert("Your name was not found!")
} else {
  alert(hits);
}

【问题讨论】:

  • 这不是在字符串中搜索“名称”,而是在搜索字母 E 的实例。
  • @Claies 谢谢我编辑它
  • 但是现在当它找到一个相似的名称时,它也会输出相似的名称,在这种情况下,我有 Eddie 和 Eric。而且我不希望它输出相似的名称。我不明白这个
  • @jonju 感谢您的关注,我现在编辑了它
  • 另外值得注意的是,这个输出不是EddieEric 两个元素的数组,它是一个单独的字符数组,[E][d][d][i][e][E][r][i][c][ ]

标签: javascript arrays string search


【解决方案1】:

这是否能满足您的需求

/*jshint multistr:true */
var text, myName, hits, i, j;
text = "Hello, there, how are you feeling Eddie hope you are ok, ok Eric";
myName = "Eddie";
var isFound=text.includes(myName);
var index= text.indexOf(myName);
if(isFound){
  alert("You name was found by using \"includes\" method");
}else{
  alert("You name was not found with \"includes\" method");
}
if(index>=0){
   alert("You name was found at "+ index +" by using \"indexOf\" method");
}else{
  alert("You name was not found with \"indexOf\" method");
}

【讨论】:

  • 它适用于 12.0 版。 See
  • 如果您可以使用 indexOf() 找到一个有效索引,这意味着您要查找的单词已包含在内,而如果您得到 -1 则该单词不存在,这有点多余
【解决方案2】:

根据你的标题,

如何修复这个程序,让它只搜索我的名字?

我对您的问题的理解可能会对您有所帮助:

        var text = "Hello, there, how are you feeling Eddie hope you are ok, ok Eric";
	var myName = 'Eddie';

	if (text.search(myName)!== -1) {
		alert('Eddie found');
	} else {
		alert('Eddie not found');
	}

【讨论】:

    【解决方案3】:

    您可以对字符串使用内置的 indexOf() 方法。

    var text = "Hello, there, how are you feeling Eddie hope you are ok, ok Eric";
    var myName = "Eddie";
    var hits = [];
    var startIndex = text.indexOf(myName);
    if (startIndex !== -1) { // myName exists in text
        for (var i = startIndex; i < startIndex + myName.length; ++i) {
            hits.push(text[i]);
        }
    }
    else {
        // Do whatever you want like.. 
        console.log("Not Found!")
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-09
      • 1970-01-01
      • 1970-01-01
      • 2011-09-24
      • 2021-07-19
      相关资源
      最近更新 更多