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

使用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日

悬赏问题

  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)