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

如何统计字符串元音数量返回整数(连续元音双倍计数)及JS代码问题修复

代码问题排查与修复方案

原代码存在的问题

  • 使用map仅逐元素判断打印,无累计计数逻辑,也没有返回最终统计结果
  • 计数变量counter定义在遍历回调内部,每次循环都会被重置为0,无法实现计数累加
  • 未实现「连续出现的元音按两倍计数」的规则,仅完成了单个元音的识别逻辑

修复实现

我们改用reduce做累计计数,同时记录前一位字符是否为元音,判断当前元音的计数权重:

const stringVowel = 'hottentottententententoonstellingsbedrijfsacademie'

const numberOfVowels = (str) => {
  const vowelSet = new Set(['a', 'o', 'u', 'e', 'i'])
  return str.split('').reduce((total, curr, index, arr) => {
    // 当前字符非元音,直接返回当前累计值
    if (!vowelSet.has(curr)) return total
    // 前一位是元音则加2,否则加1
    return total + (index > 0 && vowelSet.has(arr[index - 1]) ? 2 : 1)
  }, 0)
}

const result = numberOfVowels(stringVowel)
console.log(result)

逻辑说明:用Set存储元音可以提升判断效率,reduce初始累计值设为0,遍历过程中实时对比前一位字符属性,匹配连续元音双倍计数的需求。

内容的提问来源于stack exchange,提问作者Arjan van der Laan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 11:54:04