需要帮助调试元音计数JS [英] Need help debugging vowel counting JS
问题描述
我需要调试一个类的代码段,我已经修复了很多东西,但我不知道为什么它不起作用。它应该计算短语中的元音数量,并将它们返回到我认为的div元素中。但是它总是返回未定义的元音
I need to debug this segment of code for a class and I have fixed a number of things but I'm not sure why it doesnt work. It is supposed to count the number of vowels in the phrase and return them in the div element i believe. However it always returns "undefined vowels"
这是html
<!doctype html>
<html>
<!-- vowels.html -->
<head>
<meta charset="utf-8">
<title>Vowels</title>
<link rel="stylesheet" href="../css/easy.css">
<script src="vowels.js"></script>
</head>
<body>
<header>
<h1>I'd like to buy a vowel</h1>
</header>
<main>
<label>
Type a phrase here:
<input type='text' id='textBox'> </input>
</label>
<button id='countBtn' type='button'> <!--changed countButton to countBtn-->
Count Vowels (a,e,i,o,u)
</button>
<div id='outputDiv'>
</div>
</main>
<footer>
<hr>
<p>© UO CIS 111 2015 April™ LLC</p>
</footer>
</body>
</html>
这里是我的JS
function countVowels() {
var textBox, phrase, i, pLength, letter, vowelCount; //removed alert count vowels
textBox = document.getElementById('textBox'); //corrected spelling of Element
phrase = textBox.value;
phrase = phrase.toLowerCase; //switched to lower case
for(i = 0; i < phrase.length; i+= 1) {
letter = phrase[i];
if (letter == 'a' || letter == 'e' || letter == 'i' || letter == 'o' || letter == 'u') { //fixed the spelling of letter. added another = in letter = 'e'
vowelCount = vowelCount + 1;
}
}
alert(vowelCount + ' vowels');
var outArea = document.getElementById('outputDiv'); //corrected to outputDiv instead of outputId and put document. in front of the getElement
outArea.innerHTML = vowelCount + ' vowels in ' + phrase;
}
function init(){
alert('init vowels');
var countTag = document.getElementById('countBtn'); //switched to semi- colon and condensed to single line
countTag.onclick = countVowels;
}
window.onload = init;
这是一个 JSFiddle
推荐答案
您还可以使用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());
这篇关于需要帮助调试元音计数JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!