我正在尝试编写一个接收字符串并计算元音数量的 javascript 函数。显示每个元音的计数,以及总计。如果每个元音都在字符串中,它工作正常,但如果例如没有 A 或 E,它将返回 null。
有没有办法拦截它并用 0 替换 null?还是有更有效的方法来实现这一目标?感谢任何可以提供帮助的人!
function countVowels(inString) {
return outString = (
"Total vowels: " + inString.match(/[aeiou]/gi).length +
"\nTotal A's: " + inString.match(/[a]/gi).length +
"\nTotal E's: " + inString.match(/[e]/gi).length +
"\nTotal I's: " + inString.match(/[i]/gi).length +
"\nTotal O's: " + inString.match(/[o]/gi).length +
"\nTotal U's: " + inString.match(/[u]/gi).length
);
}
<form>
Enter a string to count its vowels. <br>
<input type="text" id="inString"><br>
<button type="button" onclick="console.log(countVowels(inString.value))">Count vowels</button>
</form>
最佳答案
你可以使用|| []
作为默认的“返回值”,以防 .match
返回 null
:
function countVowels(inString) {
return outString = (
"Total vowels: " + (inString.match(/[aeiou]/gi) || []).length +
"\nTotal A's: " + (inString.match(/a/gi) || []).length +
"\nTotal E's: " + (inString.match(/e/gi) || []).length +
"\nTotal I's: " + (inString.match(/i/gi) || []).length +
"\nTotal O's: " + (inString.match(/o/gi) || []).length +
"\nTotal U's: " + (inString.match(/u/gi) || []).length
);
}
<form>
Enter a string to count its vowels. <br>
<input type="text" id="inString"><br>
<button type="button" onclick="console.log(countVowels(inString.value))">Count vowels</button>
</form>
另外,请注意我从所有单字符匹配项中删除了 []
。在正则表达式中,[a]
和 a
是等价的。
||
将返回运算符的左侧,如果该侧是 "truthy" .
如果左边是"falsy" , ||
将始终返回语句的右侧,这是我们的默认值。
如果 .match
找到任何结果,它会返回一个数组,该数组是“真实的”。
如果 .match
没有找到任何结果,它返回 null
,这是“falsy”。
关于Javascript 正则表达式匹配出现空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46703511/