【问题标题】:Do not understand vowel count code for javascript?不懂 javascript 的元音计数代码?
【发布时间】:2018-10-24 17:49:15
【问题描述】:
function getCount(str) {
  return (str.match(/[aeiou]/ig)||[]).length;
}

code-war 中的这段代码计算字符串中元音的数量。它工作得很好;但是,我试图了解它是如何工作的。

【问题讨论】:

  • 它遍历您发送的字符串并找到所有“aeiou”字符并返回它的数量(您插入其中的数组的长度。
  • 到底是哪一部分的问题?正则表达式? || 运算符?
  • str.match(/[aeiou]/ig) 返回一个包含所有匹配正则表达式的字符的数组,.length 返回数组的长度。
  • 这个函数使用Regular Expressions来匹配字母[aeiou]。 'ig' 告诉匹配项匹配不考虑大小写(字母 'i'),并在全局范围内列出所有匹配项(字母 'g')。
  • 知道了,谢谢你的帮助

标签: javascript


【解决方案1】:

/[aeiou]/iga regular expression,它将匹配任何元音。它将匹配aeioui 标志 (/[aeiou]/ig) 中的任何一个 -不敏感,g 标志代表“全局”或换句话说“在第一次匹配后不要停止”。

String#match 方法采用正则表达式并返回任何匹配项。因此,使用上面的正则表达式,您将传递一个单词并返回其中所有元音的数组。例如

var resultOfStringMatch = "The quick brown fox jumps over the lazy dog".match(/[aeiou]/ig);

console.log(resultOfStringMatch)

有一种特殊情况——如果初始字符串没有任何元音,那么输出将是值null

var resultOfStringMatch = "Th qck brwn fx jmps vr th lzy dg".match(/[aeiou]/ig);

console.log(resultOfStringMatch)

为此,使用||[] will return an empty array if the preceding value is falsey

console.log(true || "some string");
console.log(false || "some string");

console.log(null || "null is a falsey value");

所以,最后表达式str.match(/[aeiou]/ig)||[]总是返回一个数组。如果你检查它的length 属性,你会发现元音的数量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-16
    • 2021-10-11
    • 2011-01-01
    • 2012-05-08
    • 1970-01-01
    • 2021-08-22
    相关资源
    最近更新 更多