You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript元音计数函数失效求助:为何结果始终为0?

问题分析与修复方案

问题根源

你的代码存在两个核心问题:

  • 你用vowels.includes(myString)检查整个字符串是否在元音数组中,而非逐个遍历字符串里的字符去匹配元音,这必然返回false,导致计数始终为0。
  • 未处理大小写差异,若字符串中出现大写元音(比如"Apple"里的A),会无法被匹配到。

修复后的代码

const myString = "Testing for vowels";

const vowels = ["a", "e", "i", "o", "u", "y"];

function countVowels(str) {
  let count = 0;
  // 遍历字符串的每个字符,同时统一转为小写避免大小写问题
  for (const char of str.toLowerCase()) {
    if (vowels.includes(char)) {
      count++;
    }
  }
  return count;
}

const result = countVowels(myString);
console.log(result); // 输出:6

关键改动说明

  • 遍历字符串的每个字符而非直接检查整个字符串,符合统计单个元音的需求。
  • 用toLowerCase()将字符统一转为小写,确保大小写元音都能被正确匹配。
  • 函数参数名改为str,避免和全局变量重名,代码更规范。

你也可以用数组方法简化实现,效果完全一致:

function countVowels(str) {
  return str.toLowerCase().split('').filter(char => vowels.includes(char)).length;
}

内容的提问来源于stack exchange,提问作者Gabrielle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 11:57:12