【问题标题】:How to count the vowels in a string and return an integer(with consecutive vowels counted twice!)? [duplicate]如何计算字符串中的元音并返回一个整数(连续元音计数两次!)? [复制]
【发布时间】:2021-12-21 16:38:23
【问题描述】:

所以我想出了这个,虽然计数器不能正常工作。

const stringVowel = ('hottentottententententoonstellingsbedrijfsacademie')

const letters = stringVowel.split('');

const numberOfVowels = arr => arr.map(num => {
    let counter = 0;
    if (num === 'a' || num === 'o' || num === 'u' || num === 'e' || num === 'i') {
    counter++
    }
    console.log(counter)
})

numberOfVowels(letters)

【问题讨论】:

  • 您在每次迭代时都重新声明 counter,因此它永远不会超过 1。您需要在 map 调用之外声明它,但您应该使用 forEach而不是map,因为您没有使用返回的数组。见:JavaScript: Difference between .forEach() and .map()

标签: javascript arrays string split


【解决方案1】:

一种选择是使用字符串match 方法并提供包含所有元音的正则表达式:

const withVowels = 'hottentottententententoonstellingsbedrijfsacademie';

const noVowels = 'wqdftzsqq';

function numberOfVowels(str) {
  return str.match(/[aeiou]/ig)?.length ?? 0;
}

console.log(numberOfVowels(withVowels));

console.log(numberOfVowels(noVowels));

编辑:更新为基于 cmets 的更强大的解决方案

【讨论】:

  • 注意,如果没有元音,这会出错,因为match()返回null
  • 考虑/[aeiou]/i,别忘了检查空?.length ?? 0
猜你喜欢
  • 2020-12-12
  • 2020-10-02
  • 2020-02-19
  • 2011-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多