reset var to blank after running loop in javascript - javascript

HELP! I have been banging my head against the wall for hours and hour trying to find a way that once my "game" has ended either by winning or losing my lettersGuessed var resets and no longer displays my userGuesses. I can get through the first loop/ round by setting lettersGuessed = ""; but when a new userGuess is entered, I get an uncaught type error that lettersGuessed is not a function.
// array of letters for the computer to chose from
var letterBank = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
var lettersGuessed = []
// variables starting value for tally counter
var wins = 0;
var losses = 0;
var guessesLeft = 6;
var compGuess = letterBank[Math.floor(Math.random() * letterBank.length)];
for (var i = 0; i <= guessesLeft; i++) {
document.onkeyup = function(event) {
// var for use of collecting key answers for both user and computer.
var userGuess = event.key;
lettersGuessed.push(userGuess);
// if statements to get a win or loss
if (userGuess === compGuess) {
guessesLeft = 7;
alert("You won!")
compGuess = letterBank[Math.floor(Math.random() * letterBank.length)];
userGuess = "";
lettersGuessed = "";
wins++;
}
if (userGuess != compGuess) {
guessesLeft--;
}
if (guessesLeft === 0) {
alert("GAME OVER");
guessesLeft = 6;
losses++;
userGuess = "";
compGuess = letterBank[Math.floor(Math.random() * letterBank.length)];
}
// variables to display a win/loss tally and the computer/user guesses
var html =
"<p> your choice: " + userGuess + "</p>" +
"<p> losses: " + losses + "</p>" +
"<p> wins: " + wins + "</p>" +
"<p> Guesses left: " + guessesLeft + "</p>" +
"<p> Your Guesses so far:" + lettersGuessed + "</p>";
// sends info collected from html var to the game div
document.querySelector("#game").innerHTML = html;
};
};
<div id="game">Type a letter</div>

lettersGuessed is an array when declared and not a string. To reset, you need to use the same code as the first initialization. So in your first if statement, replace
lettersGuessed = "";
with
lettersGuessed = [];

Related

Guess the number game: progressing the loop / alert + reset

I want to create a "Guess the numbers game" where you guess a random number within a certain amount of attempts.
I struggle with:
(Must have)
1. Progressing in the loop after the alert (which shows you if your guess was to high, too low, or not a number.
(Nice to have)
2. Resetting the game if you managed to guess the number or ran out of attempts. Resetting means to restore the original amount of guesses and zeroing your attempts. Maybe just a command that refreshes the page.
I'm - after years of break after my first attempts - new to coding.
Here is access to my project: https://glitch.com/~gravel-pyrite
I think this is the relevant loop/conditions engine where I mess up:
var rangeMin = 0; //set the min value
var rangeMax = 10; //set the max value
var randomNumber = Math.floor(Math.random() * (rangeMax - rangeMin + 1)) + rangeMin;
var counter = 0;
var maxTries = 5;
var remainingTries = maxTries;
var guessedNumbers = [];
document.getElementById("submit").onclick = function() {
//Displaying min, max and remaining guesses in HTML
document.getElementById('min').innerHTML = rangeMin;
document.getElementById('max').innerHTML = rangeMax+"!";
document.getElementById('feedback').innerHTML = "Remaining guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
var attempts = +document.getElementById("guessInput").value; // use `+` to make sure your input value is treated as a number and not a string
guessedNumbers.push(" "+attempts+" ");
counter++;
remainingTries--;
if (counter >= maxTries) { //If running outs of attempts, break out of loop (test for >= to)
alert("You used up your maximum tries. A new game will start.");
resetGame();
} else if (isNaN(attempts)) { //If anything else than a number is entered
alert(attempts + " is not a number");
} else if (attempts == randomNumber) { //If guessed correctly
alert("Awesome! You guessed the number right: " + randomNumber + ". You needed " + attempts + " attempts.");
resetGame();
} else if (attempts > randomNumber && counter < maxTries) {
alert("Your guess " + attempts + " is too high. Guess lower.")
} else if (attempts < randomNumber && counter < maxTries) {
alert("Your guess " + attempts + " is too low. Guess higehr.")
}
}
function resetGame() {
location.reload(true);
}
I expect that after the alerts, I can enter a new value, instead I get stuck in an "alerts loop".
EDIT: I've updated my code now. Reloading the page in after succeeding using up all tries works well.
One thing open:
document.getElementById('feedback').innerHTML = "Remaining guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
won't only show after the first time the button was submitted.
This is the HTML:
<body>
<h1>Guess what!</h1>
<p>Guess a number between <span id="min"></span> & <span id="max"></span></p>
<div>
<label for="guessInput">Your guess</label>
<input type="text" id="guessInput">
<input type="submit" id="submit">
</div>
<p id="feedback"></p>
<p id="guessedNumbers"></p>
<button onclick="resetGame()">Reset Game</button>
</body>
Adjusted your code
See fiddle example: https://jsfiddle.net/u0cmtg7j/1/
You don't need a loop, do everything in you submit event.
Also move your DOM manipulation code inside your submit event since you want to update the HTML every time your result changes.
Suggestions:
pack you DOM/HTML manipulation code in a function so that is nice and re-usable.
JS
var rangeMin = 0; //set the min value
var rangeMax = 10; //set the max value
var randomNumber = Math.floor(Math.random() * (rangeMax - rangeMin + 1)) + rangeMin;
var counter = 0;
var maxTries = 5;
var remainingTries = maxTries;
var guessedNumbers = [];
//Prompt that asks user to guess a number between x / 10
//Check if number is correct
//If wrong, prompt them to guess again unti they run out of guesses
//If correct, tell them they won, the number of attempts and thank you
document.getElementById("submit").onclick = function() {
var attempts = document.getElementById("guessInput").value;
guessedNumbers.push(attempts);
counter++;
remainingTries--;
if (counter > maxTries) { //If running outs of attempts, break out of loop
alert("You used up your maximum tries.");
resetGame();
} else if (isNaN(attempts)) { //If anything else than a number is entered
alert(attempts + " is not a number");
} else if (attempts == randomNumber) { //If guessed correctly
alert("Awesome! You guessed the number right: " + randomNumber + "You needed " + attempts + " attempts.");
resetGame();
} else if (attempts > randomNumber && counter < maxTries) {
alert("Your guess " + attempts + " is too high. Guess lower.")
} else if (attempts < randomNumber && counter < maxTries) {
alert("Your guess " + attempts + " is too low. Guess higer.")
}
document.getElementById('min').innerHTML = rangeMin;
document.getElementById('max').innerHTML = rangeMax + "!";
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
}
function resetGame() {
}
//Displaying min, max and remaining guesses in HTML
document.getElementById('min').innerHTML = rangeMin;
document.getElementById('max').innerHTML = rangeMax + "!";
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
HTML
<h1>Guess what!</h1>
<p>Guess a number between <span id="min"></span> & <span id="max"></span></p>
<div>
<label for="guessInput">Your guess</label>
<input type="text" id="guessInput">
<input type="submit" id="submit">
</div>
<p id="feedback"></p>
<p id="guessedNumbers"></p>
<button>Reset Game</button>
There is no need for you to loop within your onclick callback method. By looping you're going to keep checking the value in guessInput without letting the user change their guess, and so the same if block will always run until the player is out of guesses. Instead, you need the click method to control when and how many times the code within your function runs, as it will allow the user to change their guess:
var rangeMin = 0; //set the min value
var rangeMax = 10; //set the max value
var randomNumber = Math.floor(Math.random() * (rangeMax - rangeMin + 1)) + rangeMin;
var counter = 0;
var maxTries = 5;
var remainingTries = maxTries;
var guessedNumbers = [];
console.log(randomNumber);
document.getElementById("submit").onclick = function() {
var attempts = +document.getElementById("guessInput").value; // use `+` to make sure your input value is treated as a number and not a string
guessedNumbers.push(attempts);
counter++;
remainingTries--;
if (counter >= maxTries) { //If running outs of attempts, break out of loop (test for >= to)
alert("You used up your maximum tries.");
// resetGame();
} else if (isNaN(attempts)) { //If anything else than a number is entered
alert(attempts + " is not a number");
} else if (attempts == randomNumber) { //If guessed correctly
alert("Awesome! You guessed the number right: " + randomNumber + "You needed " + attempts + " attempts.");
//resetGame();
} else if (attempts > randomNumber && counter < maxTries) {
alert("Your guess " + attempts + " is too high. Guess lower.")
} else if (attempts < randomNumber && counter < maxTries) {
alert("Your guess " + attempts + " is too low. Guess higer.")
}
}
<input id="guessInput" type="number" />
<button id="submit">Guess</button>
This is my result. I'm sure things can be improved but all works functionally:
var rangeMin = 0; //set the min value
var rangeMax = 10; //set the max value
var randomNumber = Math.floor(Math.random() * (rangeMax - rangeMin + 1)) + rangeMin;
var counter = 0;
var maxTries = 5;
var remainingTries = maxTries;
var guessedNumbers = [];
//Displaying min, max and remaining guesses in HTML
document.getElementById('min').innerHTML = rangeMin;
document.getElementById('max').innerHTML = rangeMax+"!";
document.getElementById('feedback').innerHTML = "Remainig guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
//The code
document.getElementById("submit").onclick = function() {
var attempts = +document.getElementById("guessInput").value; // use `+` to make sure your input value is treated as a number and not a string
guessedNumbers.push(" "+attempts+" ");
counter++;
remainingTries--;
if (counter >= maxTries) { //If running outs of attempts, break out of loop (test for >= to)
document.getElementById('feedback').innerHTML = "Remainig guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;alert("You used up your maximum tries. A new game will start.");
resetGame();
} else if (isNaN(attempts)) { //If anything else than a number is entered
document.getElementById('feedback').innerHTML = "Remainig guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
alert(attempts + " is not a number");
} else if (attempts == randomNumber) { //If guessed correctly
document.getElementById('feedback').innerHTML = "Remainig guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
alert("Awesome! You guessed the number right: " + randomNumber + ". You needed " + attempts + " attempts.");
resetGame();
} else if (attempts > randomNumber && counter < maxTries) {
document.getElementById('feedback').innerHTML = "Remainig guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
alert("Your guess " + attempts + " is too high. Guess lower.")
} else if (attempts < randomNumber && counter < maxTries) {
document.getElementById('feedback').innerHTML = "Remainig guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
alert("Your guess " + attempts + " is too low. Guess higehr.")
}
}
function resetGame() {
location.reload(true);
}
I saw your question yesterday, I prepared an answer for you but I found that you have deleted your question :) .
I use console.log(someVariable); before using it in my code so that I make sure it exists and not null or undefined
when I did this with your code I found that the variable 'random' existed when I declared it and assign it, but inside the event handler function it becomes 'undefined' because the function is asynchronous
the working code is the following with simplified logic
var rangeMin = 0;
var rangeMax = 10;
var remainingGuesses = 4;
document.getElementById('min').innerHTML = rangeMin;
document.getElementById('max').innerHTML = rangeMax + "!";
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingGuesses;
var random;
var guessesMade = 0;//the user hasn't guessed anything yet os we'll declare and assign the variable as zero
document.getElementById("submit").onclick = function guess() {
//this is a new guess from the user, lets increase the counter of guesses made and decrease remaining guesses
guessesMade++;
remainingGuesses--;
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingGuesses;
//lets assign the variable random a number
random = Math.floor(Math.random() * (rangeMax - rangeMin + 1)) + rangeMin;
//lets get what the user guessed
var userGuess = document.getElementById("guessInput").value;
if (random == userGuess) {
alert("CONGRATULATIONS!!! GUESSES NEEDED: " + guessesMade);
//Resetting:
remainingGuesses = 4;
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingGuesses;
}
else {
//So the user didn't guess it right, there two scenarios:
//1- user already consumed his chances, we'll alert him about it and reset the game
//2- user still has guesses to make, we will test and advise him
if (remainingGuesses == 0) {
// scenario (1-)
alert("SORRY, YOUR RAN OUT OF GUESSES. LETS PLAY AGAIN!");
remainingGuesses = 4;
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingGuesses;
}
else {
//scenario (2-)
//we will check the value of his guess and advise him
if (random > userGuess) {
alert("SORRY, YOUR GUESS " + userGuess + " IS SMALLER THEN THE NUMBER IN QUESTION." + "\n" + "CHOOSE A HIGHER NUMBER");
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingGuesses;
}
else if (random < userGuess) {
alert("SORRY, YOUR GUESS " + userGuess + " IS HIGHER THEN THE NUMBER IN QUESTION." + "\n" + "CHOOSE A SMALLER NUMBER");
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingGuesses;
}
}
}
}

Replacing a conditional statement with a loop

I am trying to make a guessing game that generates a random number which the user guesses. This guessing game must use some kind of loop. Right now it is enclosed in a function that is called when the user clicks a button, and a boolean that limits the number of guesses the user can make.
To my understanding, a loop runs without stopping until its conditions have been satisfied. If I were to have a loop in this situation, the final output would be the loop's last iteration. NumGuesses would have a value of 6 because that was when the loop stopped. How can I replace the conditional with a loop and still have it work?
//Declare variables and constants
var guessesLeft; //number of guesses the user has left
var userGuess; //user's guess
var highLimit = 1000; //high parameter
var numGuesses = 1; //number of guesess the user has guessed
var allowedGuesses = 6; //number of allowed guesses
var NL = "\n"; //new line
//function to be called when the user presses Submit Guess
function guessingGame() {
//random number that is generated
var randNum = Math.floor(Math.random() * highLimit + 1);
if (numGuesses <= allowedGuesses) {
userGuess = prompt("Enter a number between 1 and " + highLimit + ": " , "")
userGuess = parseInt(userGuess);
guessesLeft = (allowedGuesses - numGuesses) + " guesses left.";
//If userGuess is in the specified parameters
//If userGuess is larger than 1 and smaller than the higher parameter
if ((userGuess > 1) && (userGuess < highLimit)) {
//If userGuess does not equal randNum
if (userGuess !== randNum) {
//If userGuess is too low
if (userGuess < randNum) {
//output
document.numForm.gameResults.value = "You guessed too low! Please guess again. " + NL + "Your current number of guesses: " + numGuesses + NL + "You have " + guessesLeft;
}
//If userGuess is too high
else if (userGuess > randNum) {
document.numForm.gameResults.value = "You guessed too high! Please guess again. " + NL + "Your current number of guesses: " + numGuesses + NL + "You have " + guessesLeft;
}//end if
}
else {
//If userGuess is correct
document.numForm.gameResults.value = "You guessed correctly!";
}//end if
}
else {
document.numForm.gameResults.value = "Your guess was out of the specified parameters. Please try again. " + NL + "Your current number of guesses: " + numGuesses + NL + "You currently have " + guessesLeft;
//user may have entered their guess wrong
numGuesses--;
}//end if
//add to number of guesses so the program stops when it reaches the allowed number
numGuesses++;
}//end outer if statement
return false;
}//end guessingGame()
It sounds like the problem statement expects you to block waiting for user input as opposed to triggering a function in response to a DOM event.
Have a look at window.prompt
Placing this in a loop would block the loop until the user responded.
Using prompt() as suggested by retrohacker and a do {} while () loop, the following code demonstrates this in action:
var minNumber = 1;
var maxNumber = 2;
var guessesLeft = 3;
var numberToBeGuessed = minNumber +
(Math.random() * (maxNumber - minNumber + 1) | 0);
var succeeded;
var message = 'Make a guess';
do {
if (prompt(message) == numberToBeGuessed) {
alert('Correct, the number is ' + numberToBeGuessed);
succeeded = true;
} else {
guessesLeft--;
message = 'Try again, ' +
guessesLeft +
' guess' + (guessesLeft > 1 ? 'es' : '') +
' left';
}
} while (!succeeded && guessesLeft)

Reversing my encrypt method

I created minor encrypt method to convert a small string based on distance between characters, but can't for the life of me figure out how to reverse it without knowing the distance between each character from the initial conversion. See image for example how it works imgur.com/Ine4sBo.png
I've already made the encrypt method here (Javascript):
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
var position;
//var oKey = "P";
function encrypt() // Encrypt Fixed
{
var sEncode = ("HI-MOM").split('');
var oKey = "P";
for (var i = 0; i < sEncode.length; i++) {
if (all.indexOf(oKey) < all.indexOf(sEncode[i])) {
position = all.indexOf(sEncode[i]) - all.indexOf(oKey);
output.value += "oKey: " + oKey + " distance to sEncode[" + i + "]: " + sEncode[i] + " Count: " + position + " Final Char: " + all[position-1] + "\n";
oKey = sEncode[i];
}
else {
position = all.length - all.indexOf(oKey) + all.indexOf(sEncode[i]);
output.value += "oKey: " + oKey + " distance to sEncode[" + i + "]: " + sEncode[i] + " Count: " + position + " Final Char: " + all[position-1] + "\n";
oKey = sEncode[i];
}
}
}
However, it's the decrypt() method that's killing me.
From what I can tell, your encrypt function can be reduced to this:
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
function encrypt(str)
{
var sEncode = str.split('');
var result = '';
var oKey = "P";
for(var i = 0; i < sEncode.length; i++)
{
result += all[(all.indexOf(sEncode[i]) - all.indexOf(oKey) + all.length - 1) % all.length];
oKey = sEncode[i];
}
return result;
}
(I got rid of the if clause by adding all.length either way, and removing it again with the remainder operator if necessary.)
From there, all you need to do is flip the operands (- all.indexOf(oKey) - 1 becomes + all.indexOf(oKey) + 1 (and since we have no more subtractions, adding all.length is no longer necessary)) and reverse the order (so oKey gets assigned the transformed value instead of the original one):
var all = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.#-?").split('');
function decrypt(str)
{
var sEncode = str.split('');
var result = '';
var oKey = "P";
for(var i = 0; i < sEncode.length; i++)
{
oKey = all[(all.indexOf(sEncode[i]) + all.indexOf(oKey) + 1) % all.length];
result += oKey;
}
return result;
}

Adding up a current variable with the previous one

I have a problem here, basically I want my Dice game to display 3 lines.
The first line says what number of the die I got
The second line adds the number I got from the first die with the second die i rolled and so on.. (basically everytime i click the button).
The third line would just count how many times I rolled the dice.
My problem is that on my second line, im not sure how I can add up my current die roll with my previous one everytime I click the button.
var count=0;
function swap_pic()
{
var x = Math.floor(Math.random()*6)+1;
var pic = document.getElementById("dice");
var xx = x+x;
count++;
document.getElementById("result").innerHTML = "You got " + x;
document.getElementById("result").innerHTML += "<br>Your score is: " + xx;
document.getElementById("result").innerHTML += "<br>Number of tries = " + count;
if (count==5)
{
document.getElementById("result").innerHTML += "<br><span style='color:red;font-weight:bold;font-size:14px;'>Game Over!</span>";
count = 0;
document.getElementById('button').setAttribute("style","visibility:hidden");
}
if (x==1)
{
pic.src = "images/die1.png";
}
else if (x==2)
{
pic.src = "images/die2.png";
}
else if (x==3)
{
pic.src = "images/die3.png";
}
else if (x==4)
{
pic.src = "images/die4.png";
}
else if (x==5)
{
pic.src = "images/die5.png";
}
else if (x==6)
{
pic.src = "images/die6.png";
}
}
Problem is this line
document.getElementById("result").innerHTML += "<br>Your score is: " + xx;
Thank you for the help guys!
Several concatenation of innerHTML should be avoided, as well as repeated else if when possible. Try this:
var count = 0;
var sum = 0;
function swap_pic() {
var x = Math.floor(Math.random() * 6) + 1;
var pic = document.getElementById("dice");
sum += x;
count++;
var html = "You got " + x;
html += "<br>Your score is: " + sum;
html += "<br>Number of tries = " + count;
if (count == 5) {
html += "<br><span style='color:red;font-weight:bold;font-size:14px;'>Game Over!</span>";
count = 0;
document.getElementById('button').setAttribute("style", "visibility:hidden");
}
document.getElementById("result").innerHTML = html;
pic.src = "images/die" + x +".png";
}
Try this on for size
//create these as global variables
var totalScore;
var rollCount;
var lastRoll;
var image;
var text;
var button;
function reload(){
totalScore = 0;
rollCount = 0;
lastRoll = 0;
image = document.getElementById('dice'); //store image element
text = document.getElementById('result'); //store result element
button = document.getElementById('button'); //store button element
button.style.visibility = visible; //restore button visibility
}
function roll(){
lastRoll = Math.floor(Math.random()*6)+1; //generate random number
rollCount++; //increase our roll counter
totalScore+= lastRoll; //add new roll to score
image.src = "images/die" +lastRoll+ ".png"; //update dice image
text.innerHTML = "You got " // generate result string
+ lastRoll
+ "<br>Your score is: "
+ totalScore
+ "<br>Number of tries = "
+ rollCount;
if(rollCount >= 5){ //end game parameter!!
text.innerHTML += "<br><span style='color:red;font-weight:bold;font-size:14px;'>Game Over!</span>"; //add game over text
button.style.visibility = 'hidden';//hide button
//reload(); //uncomment to reset game now?
}
}
window.onload = reload; //set up on page load

Vowel counter not working in Pure js

I have made a vowel counter in pure js but I cannot get the counters to work properly. and i cannot seem to find out where i am going wrong just need a little push or example to know how to fix this if that is ok. Can someone please help me thanks in advance.
This is my HTML:
<h1> Vowel Counter </h1>
Please enter text for your vowel count:
<br>
<textarea id="text" rows="10" style="width: 100%;"></textarea>
<br>
<button onclick="countVowels();">Count Vowels</button>
<p id="result"></p>
This is my Javascript:
function countVowels() {
var text = document.getElementById("text").value;
var arrayOfLetters = text.split("");
var arrayOfVowels = ("AEIOU");
// Set up our counters
var countA = 0;
var countE = 0;
var countI = 0;
var countO = 0;
var countU = 0;
// Output the results:
document.getElementById("result").innerHTML = "";
document.getElementById("result").innerHTML += "Total Letters: " + arrayOfLetters.length + "<br />";
document.getElementById("result").innerHTML += "A's: " + arrayOfVowels.length + countA + "<br />";
document.getElementById("result").innerHTML += "E's: " + arrayOfVowels.length +countE + "<br />";
document.getElementById("result").innerHTML += "I's: " + arrayOfVowels.length +countI + "<br />";
document.getElementById("result").innerHTML += "O's: " + arrayOfVowels.length +countO + "<br />";
document.getElementById("result").innerHTML += "U's: " + arrayOfVowels.length +countU + "<br />";
}
And a have attached my jsfiddle:
http://jsfiddle.net/Matt1990/3Ckw2/43/
I would recommend using regular expressions instead of loops and so many if conditions. The complexity and maintainability of the code is bad in the above solutions unless you consider regex as not being pure js.
var countA = text.match(/[Aa]/g).length;
This will give you direct count. For finding maxval, use basic sort algorithms to find the max and then assign a css style class to it. That is not a technical problem to solve.
How are you counting the vowels?
Right now it is showing 50 for each vowel count because arrayOfVowels.length = 5 and countA (for example), is simply 0. You aren't adding any numbers together, but you're adding 5 to the string 0 which results in "50".
You simply have no mechanism to count vowels, it's not that your "vowel counter" doesn't work. You set up everything correctly but fail to work through the text and systematically count the vowels. You can improve this code by automatically making the letters lower or upper case, so you don't have to use the or operator to check for both cases. I could've done that fast but I am just too lazy...
This vowel counter will work:
function countVowels() {
var text = document.getElementById("text").value;
var arrayOfLetters = text.split("");
var arrayOfVowels = ("AEIOU");
// Set up our counters
var countA = 0;
var countE = 0;
var countI = 0;
var countO = 0;
var countU = 0;
for(i=0; i < arrayOfLetters.length; i++) {
if (arrayOfLetters[i] == "A" || arrayOfLetters[i] == "a") {
countA ++;
}
if (arrayOfLetters[i] == "E" || arrayOfLetters[i] == "e") {
countE ++;
}
if (arrayOfLetters[i] == "I" || arrayOfLetters[i] == "i") {
countI ++;
}
if (arrayOfLetters[i] == "O" || arrayOfLetters[i] == "o") {
countO ++;
}
if (arrayOfLetters[i] == "U" || arrayOfLetters[i] == "u") {
countU ++;
}
}
// Output the results:
document.getElementById("result").innerHTML = "";
document.getElementById("result").innerHTML += "Total Letters: " + arrayOfLetters.length + "<br />";
document.getElementById("result").innerHTML += "A's: " + countA + "<br />";
document.getElementById("result").innerHTML += "E's: " + countE + "<br />";
document.getElementById("result").innerHTML += "I's: " + countI + "<br />";
document.getElementById("result").innerHTML += "O's: " + countO + "<br />";
document.getElementById("result").innerHTML += "U's: " + countU + "<br />";
}

Categories

Resources