且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

需要帮助调试元音计数JS

更新时间:2023-09-18 22:19:34

您还可以使用RegExp来更细的代码: http://jsfiddle.net/4o67u3js/

You can also use RegExp for slimmer code: http://jsfiddle.net/4o67u3js/

HTML:

<p id = "text">
    Lorem ipsum dolor sit amet.
</p>
<p id = "result"># of vowels: <span></span></p>

JS:

$(function() {
    var vowelsCount = $("#text").text().match(/[aeiou]/gi).length;
    $("#result > span").html(vowelsCount);
});

这是一个更加算法的解决方案。而且,是的,它定义了一个原型的功能,那些反对这种做法的人可以强制重写该功能。

Here's a more algorithmic solution. And, yes it defines a function on the prototype and those who are opposed to that practice can rewrite the function imperatively.

平原JS:

var str = "Lorem ipsum dolor sit amet.";

String.prototype.vowelsCount = function() {
    var str = this.toLowerCase(),
        len = str.length,
        index = 0,
        vowels = ["a", "e", "i", "o", "u"],
        count = 0;

    for( ; index < len; vowels.indexOf(str[index++]) !== -1 ? count++ : count);

    return count;
};

console.log(str.vowelsCount());