【问题标题】:Javascript for loop & arrays用于循环和数组的 Javascript
【发布时间】:2013-07-19 12:06:59
【问题描述】:

我正在运行以下代码来获取显示单词 Eric 的字母的相关输出。

/*jshint multistr:true */

text = "My name is Eric. Eric lives in New York";
var myName = "Eric";
var hits = [];

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

我能够获得所需的输出 [ 'E', 'r', 'i', 'c', 'E', 'r', 'i', 'c' ]

但是,当我在代码的第 8 行输入 "l" 时,我得到以下输出: ['l'、'i'、'v'、'e'、's'、''、'i']

根据我的理解,代码应该返回一条消息找不到你的名字!

相反,它仍在处理字母 l 之后的字符并将其作为输出返回。

如何以更好的方式优化我的代码,以确保仅搜索字符串 Eric 中的字符并将其作为输出返回,而拒绝任何其他字符?

【问题讨论】:

  • 为什么要说找不到名字?您的代码中没有任何内容可以将 myName 与文本进行比较。它所做的只是使用myName.length 作为for 循环限制的一部分,但它对myName 中的字符没有任何作用。
  • 如果你想知道名字是否在文本中找到,为什么不使用text.indexOf(myName)
  • 我已经测试了你的代码,但它的行为不像你说的那样。
  • 您能解释一下您的代码的用途吗?也许有一种更简单的方法可以实现您想要的。

标签: javascript arrays loops for-loop


【解决方案1】:

如果 Eric 完全匹配,则只需将其放入数组中。

例如(Eric 在数组中,但 Eriic 不在)

工作演示http://jsfiddle.net/9UcBS/1

text = "My name is Eric. Eric lives in New York Eriic";
var myName = "Eric";
var hits = [];

var pos = text.indexOf(myName);
while (pos > -1) {
    for (var j = pos; j < (myName.length + pos); j++) {
        hits.push(text[j]);
    }
    pos = text.indexOf(myName, pos + 1);
}
(hits.length === 0) ? console.log("Your name wasn't found!") : console.log(hits);

【讨论】:

    【解决方案2】:

    在这种情况下使用正则表达式会容易得多:

    var name = "Eric";
    var text = "My name is Eric. Eric lives in New York";
    var hits = [];
    var regexp = new RegExp(name, "g");
    var match;
    while (match = regexp.exec(text)) {
        hits.push(match[0]);
    }
    console.log(hits);
    

    当使用带有“g”标志的exec 时,每次调用都会推进字符串中的位置。所以在第一次迭代中,你会得到第一个 Eric,然后第二个会找到下一个,以此类推。如需更多信息,请参阅mdn

    在此循环之后,命中将是字符串“Eric”的数组。如果你想要像以前一样的字符数组,你可以使用一个简单的技巧:

    while (match = regexp.exec(text)) {
        hits = hits.concat([].slice.call(match[0]));
    }
    

    或者如果你想直接使用 for 循环:

    while (match = regexp.exec(text)) {
        for (var i = 0; i < match[0].length; i++) {
            hits.push(match[0][i]);
        }
    }
    

    【讨论】:

      【解决方案3】:

      字符串不是字符数组。要从字符串的位置获取字符,需要使用charAt 方法,如下所示:

      if ( text.charAt(i) == "E" ) {
          //...
      }
      

      甚至更好:

      if ( text.charAt(i) == myName.charAt(0) ) {
          //...
      }
      

      【讨论】:

        【解决方案4】:

        使用 indexOf() 查找字符串出现的一个很好的示例位于:https://stackoverflow.com/a/3410557/2577572

        上面链接的示例的结果将为您提供您正在搜索的字符串的位置数组。如果调用上面详述的函数后数组没有长度,那么你的名字没有找到。

        我认为您实际上不需要创建一个由搜索字符串组成的字母数组,因为根据您的示例,它们每次都与搜索字符串相同。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-05-28
          • 2012-07-09
          • 2018-04-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多