李奉典 2023-10-09 20:32 采纳率: 93.1%
浏览 17
已结题

使用JavaScript语句,统计包含“a”或“A”的字符串的个数。出现的错误

使用JavaScript语句,统计包含“a”或“A”的字符串的个数。第一段代码是正确答案,第二段代码是我写的,看起来和答案一样,但是执行结果只显示数组的第一个字符串,请问这是为什么,检查很久了,,
正确答案:


<!DOCTYPE html>
<html>
  <head lang="en">
    <meta charset="UTF-8" />
    <title>统计包含“a”或“A”的字符串的个数</title>
  </head>
  <body>
    <script type="text/javascript">
      var countryList = [
        "America",
        "Greece",
        "Britain",
        "Canada",
        "China",
        "Egypt",
      ];
      var count = 0;
      document.write("在以下字符中:<br/>");
      for (var i in countryList) {
        document.write(countryList[i] + "<br/>");
        if (
          countryList[i].indexOf("a") != -1 ||
          countryList[i].indexOf("A") != -1
        )
          count++;
      }
      document.write("共有" + count + "个字符中串包含a或A。");
    </script>
  </body>
</html>

答案的执行结果如图:

img

我写的:

<!DOCTYPE html>
<html>
  <head lang="en">
    <meta charset="UTF-8" />
    <title>统计包含“a”或“A”的字符串的个数</title>
  </head>
  <body>
    <script type="text/javascript">
      var countryList = [
        "abc",
        "America",
        "Greece",
        "Britain",
        "Canada",
        "China",
        "Egypt",
      ];
      var count = 0;
      document.write("在以下字符中:<br/>");
      for (var i in countryList) {
        document.write(countryList[i] + "<br/>");
        if (
          countryList[i].indexof("a") != -1 ||
          countryList[i].indexof("A") != -1
        )
          count++;
      }

      document.write("有" + count + "个字符串包含字符a·A " + "<br>");
    </script>
  </body>
</html>


执行结果:

img

  • 写回答

2条回答 默认 最新

  • Leodong. 2023-10-09 20:36
    关注

    你的代码中,indexOf方法的拼写错误导致了问题。正确的拼写应该是indexOf,O需要大写!而不是indexof。请将indexof修改为indexOf,然后再次运行代码。


    如果以上回答对您有所帮助,点击一下采纳该答案~谢谢

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 10月18日
  • 已采纳回答 10月10日
  • 创建了问题 10月9日