simple beginner search program using arrays in javascript, issue with displaying

放肆的年华 提交于 2019-12-25 06:15:42

问题


I am creating a simple search program that searches for my name block of text. The issue I am having is at the end, when I place the letters in the array, they seem to come out a single character on each line, rather than uniformly in one single block of text. Can anyone point out the discrepancy?

var text = "hah hah Aaron hah hah Aaron\
hah hah hah hah hoh Aaron hah hah hah hah\
Aaron Aaron Aaron hah";
var myName = "Aaron";
var hits = [];

for (var i =0; i< text.length; i++) {
    if (text[i] === "A") {
       for (var j = i; j <(myName.length + i); j++){
        hits.push(text[j]);
       } 
    }
}
if (hits === 0) {
    console.log ("Your name wasn't found!");
}
else {
    console.log(hits);
}

回答1:


The reason of "letter by letter" behaviour is that variable hits contains an array of single letters from all the matches.

You either need to call join method on array with letters from one name found, or use something more advanced instead of cycles. For example, text.match(/Aaron/g) will return an array of all names matched.




回答2:


I think this search program is much more valid:

var text = "Blah blah blah blah blah blah Eric \
blah blah blah Eric blah blah Eric blah blah \
blah blah blah blah blah Eri Epic Erics☺n"
var name = "Eric"
var x=0;
var y=0

for (var i = 0; i < text.length; i++) {
  x=0;
  for (var j = i; j < name.length + i; j++) {
    if (text[j] === name[j-i]) {
      x++;
      if(x === name.length) {
        y++
      }
    }
  }
}
console.log("Found "+y+" times")


来源:https://stackoverflow.com/questions/15996731/simple-beginner-search-program-using-arrays-in-javascript-issue-with-displaying

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!