Trying to push a letter into an array to display on page - javascript

var secretWord = [];
var underScoreWord = [];
var wins = 0;
var guessesRemaining = 10;
var alreadyGuessed = [];
var wordLetter = true;
//Assign HTML elements to variables
var cityText = document.getElementById("city-text");
var winsNum = document.getElementById("wins-num");
var guessesNum = document.getElementById("guesses-num")
var lettersGuessed = document.getElementById("letters-guessed")
//Array of cities
var city = ["Paris", "Wellington", "Hanoi", "Perth", "Marseille", "London", "Ottawa", "Zurich", "Boston", "Tokyo", "Detroit"];
//console.log(city);
//Pick random word from the team array and push the result to an empty array.
function pickRandomCity() {
var randomCity = city[Math.floor(Math.random() * city.length)];
secretWord = randomCity.split('');
return randomCity;
}
var cityPicked = pickRandomCity();
//Get length of secretWord and push as underscores to am empty array
for (var i = 0; i < cityPicked.length; i++) {
underScoreWord.push("_");
}
console.log('secretWord : ' + secretWord);
// console.log('underScoreWord : ' + underScoreWord);
// console.log('------------------');
// console.log('cityPicked : ' + cityPicked);
//Check for letters
//Listen for key press and check to see if its a match
document.onkeyup = function letterCheck(event) {
var userGuess = event.key;
for (var j = 0; j < secretWord.length; j++) {
if (userGuess.toUpperCase() === secretWord[j].toUpperCase()) {
wordLetter = true;
underScoreWord[j] = userGuess;
guessesRemaining--;
}
else if (!wordLetter) {
alreadyGuessed.push();
// guessesRemaining--;
}
}
console.log("Already guessed: " + alreadyGuessed);
lettersGuessed.textContent = ("Letters already guessed: " + alreadyGuessed);
// Write to page
cityText.textContent = underScoreWord.join(" ");
winsNum.textContent = ("Wins: " + wins);
guessesNum.textContent = ("Guesses Remaining: " + guessesRemaining);
console.log(underScoreWord);
}
Does anybody know how can I push userGuess to an empty array and then display? As you can see I managed to push the userGuess to the alreadyGuessed array but it only displays one character at a time on the page.
The end goal is for the alreadyGuessed array to display like this - Letters alreadyGuessed: a g r h e t

You can store what keys have been pressed with an object, and at the beginning of each keyup event, check if user has pressed it.
I also switched the for loop to map
var guessedLetters = {};
document.onkeyup = function letterCheck(event) {
var userGuess = event.key;
if (!guessedLetters[userGuess.toUpperCase()]) { // check if user pressed this key
alreadyGuessed.push(userGuess.toUpperCase());
guessedLetters[userGuess.toUpperCase()] = true;
guessesRemaining--;
} else { // this key has been pressed before, dont do anything
return;
}
secretWord.map((n, i) => {
if (userGuess.toUpperCase() === n.toUpperCase()) {
underScoreWord[i] = n;
}
})
console.log("Already guessed: " + alreadyGuessed);
lettersGuessed.textContent = ("Letters already guessed: " + alreadyGuessed);
// Write to page
cityText.textContent = underScoreWord.join(" ");
winsNum.textContent = ("Wins: " + wins);
guessesNum.textContent = ("Guesses Remaining: " + guessesRemaining);
console.log(underScoreWord);
}

Looks like wordLetter is a global variable initialized to true. Also looks like it is never set to false so your call to alreadyGuessed.push(userGuess); will never be reached since !wordLetter is always false.

Try alreadyGuessed.push(userGuess); inside your event listener's elseif statement.
EDIT:
As per the suggestion from #foxinatardis, the way you modify and check for wordLetter inside your loop needs to be changed:
if (userGuess.toUpperCase() === secretWord[j].toUpperCase()) {
wordLetter = true;
underScoreWord[j] = userGuess;
guessesRemaining--;
} else {
wordLetter = false;
alreadyGuessed.push(userGuess);
// guessesRemaining--;
}
You actually don't need the wordLetter variable anymore with this change, unless you're using it elsewhere for something else.

Related

Trouble preventing duplicate letter entry in pure JS hangman

So, I'm coding out a hangman style game as is the custom when learning how to user JS. I have it working pretty well, but I cannot seem to figure out how to properly identify and prevent duplicate wrong guesses.
Example: if you press "f" and it is not in the word, display and decrement the remaining scores once, and if you press "f" again, ignore the input. Here is my code thus far. I have my existing code in the function but it doesn't currently do anything. Any advice is appreciated.
// words to guess will be selected from here
var wordSelectionArray = [
"adventure", "bandit", "battleaxe", "battlefield", "beholder", "bugbear", "castle", "catapult", "cleric", "dragon", "dungeon",
"fairy", "fireball", "giant", "goblin", "knight", "magic", "monster", "necromancer", "owlbear", "paladin", "potion", "quarterstaff",
"sorcerer", "spells", "sword", "vampire", "warlock", "wizard", "zombie"]
//variable to hold the randomly selected word
var selectedWord = "";
//variable to store number of blanks
var blanks = 0;
//var to hold the split out array of the randomly selected word.
var letters = [];
//var to store blanks with the correct word
var blankAndCorrect = [];
//var to hold the incorrect letter guesses when input by the user.
var wrongGuess = [];
// start the game with a score of zero
var wins = 0;
var losses = 0;
//variable to hold number of guesses remaining
var guessesRemaining = 12;
//array for guessed letters
var alreadyGuessedLetters = [];
//variable to hold the background music
var myMusic = document.getElementById("background-music");
function game() {
selectedWord = wordSelectionArray[Math.floor(Math.random() * wordSelectionArray.length)];
letters = selectedWord.split("");
blanks = selectedWord.length;
for (var i = 0; i < blanks; i++) {
blankAndCorrect.push("_");
}
document.getElementById("current-word").innerHTML = " " + blankAndCorrect.join(" ");
myMusic.play();
// console.log(selectedWord);
// console.log(letters);
// console.log(blanks);
// console.log(blankAndCorrect);
};
//function to start the game over
function reset() {
guessesRemaining = 12;
wrongGuess = [];
blankAndCorrect = [];
game();
};
//check and compare function
function checkInput(letter) {
letterInWord = false;
for (var i = 0; i < blanks; i++) {
if (selectedWord[i] == letter) {
letterInWord = true;
}
} if (letterInWord) {
for (var i = 0; i < blanks; i++) {
if (selectedWord[i] == letter) {
blankAndCorrect[i] = letter;
}
}
} if (letterInWord) {
for (var i = 0; i < alreadyGuessedLetters.length; i++) {
if (selectedWord[i] !== letter) {
alreadyGuessedLetters[i] = letter;
return;
}
}
} else {
wrongGuess.push(letter);
alreadyGuessedLetters.push(letter);
guessesRemaining--;
console.log(alreadyGuessedLetters);
}
};
//function to check wins/losses
function completeGame () {
if (letters.toString() == blankAndCorrect.toString()) {
wins++;
document.getElementById("correct-answer-message").innerHTML = "Great Job! " + selectedWord.toLocaleUpperCase() + " was the word!" ;
reset();
document.getElementById("wins").innerHTML = " " + wins;
} else if (guessesRemaining === 0) {
losses++;
reset();
document.getElementById("losses").innerHTML = " " + losses;
}
document.getElementById("current-word").innerHTML = " " + blankAndCorrect.join(" ");
document.getElementById("guesses-remaining").innerHTML = " " + guessesRemaining;
};
game();
document.onkeyup = function (event) {
var guesses = String.fromCharCode(event.keyCode).toLowerCase();
checkInput(guesses);
completeGame();
// console.log(guesses);
document.getElementById("letters-guessed").innerHTML = " " + wrongGuess.join(" ");
}
See how I'm ignoring duplicates in checkInput.
// words to guess will be selected from here
var wordSelectionArray = [
"adventure", "bandit", "battleaxe", "battlefield", "beholder", "bugbear", "castle", "catapult", "cleric", "dragon", "dungeon",
"fairy", "fireball", "giant", "goblin", "knight", "magic", "monster", "necromancer", "owlbear", "paladin", "potion", "quarterstaff",
"sorcerer", "spells", "sword", "vampire", "warlock", "wizard", "zombie"]
//variable to hold the randomly selected word
var selectedWord = "";
//variable to store number of blanks
var blanks = 0;
//var to hold the split out array of the randomly selected word.
var letters = [];
//var to store blanks with the correct word
var blankAndCorrect = [];
//var to hold the incorrect letter guesses when input by the user.
var wrongGuess = [];
// start the game with a score of zero
var wins = 0;
var losses = 0;
//variable to hold number of guesses remaining
var guessesRemaining = 12;
//array for guessed letters
var alreadyGuessedLetters = [];
//variable to hold the background music
var myMusic = document.getElementById("background-music");
function game() {
selectedWord = wordSelectionArray[Math.floor(Math.random() * wordSelectionArray.length)];
letters = selectedWord.split("");
blanks = selectedWord.length;
for (var i = 0; i < blanks; i++) {
blankAndCorrect.push("_");
}
document.getElementById("current-word").innerHTML = " " + blankAndCorrect.join(" ");
// myMusic.play();
// console.log(selectedWord);
// console.log(letters);
// console.log(blanks);
// console.log(blankAndCorrect);
};
//function to start the game over
function reset() {
guessesRemaining = 12;
wrongGuess = [];
blankAndCorrect = [];
game();
};
//check and compare function
function checkInput(letter) {
if (wrongGuess.includes(letter)) { // <--- HERE
// do anything else you wanna do
return;
}
letterInWord = false;
for (var i = 0; i < blanks; i++) {
if (selectedWord[i] == letter) {
letterInWord = true;
}
} if (letterInWord) {
for (var i = 0; i < blanks; i++) {
if (selectedWord[i] == letter) {
blankAndCorrect[i] = letter;
}
}
} if (letterInWord) {
for (var i = 0; i < alreadyGuessedLetters.length; i++) {
if (selectedWord[i] !== letter) {
alreadyGuessedLetters[i] = letter;
return;
}
}
} else {
wrongGuess.push(letter);
alreadyGuessedLetters.push(letter);
guessesRemaining--;
console.log(alreadyGuessedLetters);
}
};
//function to check wins/losses
function completeGame () {
if (letters.toString() == blankAndCorrect.toString()) {
wins++;
document.getElementById("correct-answer-message").innerHTML = "Great Job! " + selectedWord.toLocaleUpperCase() + " was the word!" ;
reset();
document.getElementById("wins").innerHTML = " " + wins;
} else if (guessesRemaining === 0) {
losses++;
reset();
document.getElementById("losses").innerHTML = " " + losses;
}
document.getElementById("current-word").innerHTML = " " + blankAndCorrect.join(" ");
document.getElementById("guesses-remaining").innerHTML = " " + guessesRemaining;
};
game();
document.onkeyup = function (event) {
var guesses = String.fromCharCode(event.keyCode).toLowerCase();
checkInput(guesses);
completeGame();
// console.log(guesses);
document.getElementById("letters-guessed").innerHTML = " " + wrongGuess.join(" ");
}
<div id="current-word"></div>
<div id="guesses-remaining"></div>
<div id="letters-guessed"></div>

Displaying a hint mode in a hangman game js UPDATE

Now after implementing the hint mode, the guessing part does not work, meaning I cannot guess a letter. This means that the lives do not reduce and no one can win or lose the game. The hint mode works perfectly.
function setup() {
alphabet = "abcdefghijklmnopqrstuvwxyz";
lives = 8;
var words = ["ayeupmeducks", "pieceofcake",
"bullinachinashop", "hangfire","greeneyedmonster",
"hairraising","bringhomethebacon","adiamondintherough","onceinabluemoon",
"afootinthedoor","bitethebullet"];
messages = {
win: 'Congratulations you have won the game of Hangman!',
lose: 'You have been Hanged !!',
guessed: ' already guessed, please try again...',
validLetter: 'Please enter a letter from A-Z'
};
var getHint = document.getElementById("hint");
var showClue = document.getElementById("clue");
getHint.onclick = function() {
hints = ["Stoke Greeting","Saying Something is Easy",
"Very Clumsy","delaying something for a minute",
"When you are jealous of something",
"Something is frightening", "Earn Money",
"Rough Exterior however has some potential",
"When something rarely happens",
"When you have succeeded/ getting yourself known by a company",
"accepting something , when you do not want to"];
var hintIndex = words
showClue.innerHTML = "Clue: - " + hints [idx];};
gussedLetter = matchedLetter = '';
numberofMatchedLetters = 0;
var idx = Math.floor(Math.random() * words.length);
var currentWord = words[idx];
output = document.getElementById("output");
message = document.getElementById("message");
guessInput = document.getElementById("letter");
message.innerHTML = 'You have ' + lives + ' lives remaining';
output.innerHTML = '';
document.getElementById("letter").value = '';
guessButton = document.getElementById("guess");
guessInput.style.display = 'inline';
guessButton.style.display = 'inline';
letters = document.getElementById("letters");
letters.innerHTML = '<li class="current-word">Current word:</li>';
var letter, i;
for (i = 0; i < currentWord.length; i++) {
letter = '<li class="letter letter' + currentWord.charAt(i).toUpperCase() + '">' + currentWord.charAt(i).toUpperCase() + '</li>';
letters.insertAdjacentHTML('beforeend', letter);
}
}
function gameOver(win) {
if (win) {
output.innerHTML = messages.win;
output.classList.add('win');
} else {
output.innerHTML = messages.lose;
output.classList.add('error');
}
guessInput.style.display = guessButton.style.display = 'none';
guessInput.value = '';
}
window.onload = setup();
document.getElementById("restart").onclick = setup;
guessInput.onclick = function () {
this.value = '';
};
document.getElementById('hangman').onsubmit = function (e) {
if (e.preventDefault) e.preventDefault();
output.innerHTML = '';
output.classList.remove('error', 'warning');
guess = guessInput.value;
if (guess) {
if (alphabet.indexOf(guess) > -1) {
if ((matchedLetter && matchedLetter.indexOf(guess) > -1) || (gussedLetter && gussedLetter.indexOf(guess) > -1)) {
output.innerHTML = '"' + guess.toUpperCase() + '"' + messages.guessed;
output.classList.add("warning");
}
else if (currentWord.indexOf(guess) > -1) {
var lettersToShow;
lettersToShow = document.querySelectorAll(".letter" + guess.toUpperCase());
for (var i = 0; i < lettersToShow.length; i++) {
lettersToShow[i].classList.add("correct");
}
for (var j = 0; j < currentWord.length; j++) {
if (currentWord.charAt(j) === guess) {
numberofMatchedLetters += 1;
}
}
matchedLetter += guess;
if (numberofMatchedLetters === currentWord.length) {
gameOver(true);
}
}
else {
gussedLetter += guess;
lives--;
message.innerHTML = 'You have ' + lives + ' lives remaining';
if (lives === 0) gameOver();
}
}
else {
output.classList.add('error');
output.innerHTML = messages.validLetter;
}
}
else {
output.classList.add('error');
output.innerHTML = messages.validLetter;
}
return false;
};
The variables as far as I can see are still the same, so I do not get why an error occurs?.
You declared an array containing an array :
hints = [
["Stoke Greeting","Saying Something is Easy", "Very Clumsy","delaying something for a minute", "When you are jealous of something","Something is frightening", "Earn Money", "Rough Exterior however has some potential", "When something rarely happens", "When you have succeeded/ getting yourself known by a company","accepting something , when you do not want to"]
];
Change it to a simple array :
hints = ["Stoke Greeting","Saying Something is Easy", "Very Clumsy","delaying something for a minute", "When you are jealous of something","Something is frightening", "Earn Money", "Rough Exterior however has some potential", "When something rarely happens", "When you have succeeded/ getting yourself known by a company","accepting something , when you do not want to"];
In addition to the array in array problem, you also need to store the index itself and use that instead of the word.
Also you have typo: hint.onclick should be getHint.onclick.
var words = ["ayeupmeducks", "pieceofcake", "bullinachinashop", "hangfire","greeneyedmonster", "hairraising","bringhomethebacon","adiamondintherough","onceinabluemoon","afootinthedoor","bitethebullet"];
var idx = Math.floor(Math.random() * words.length);
var currentWord = words[idx];
var getHint = document.getElementById("hint");
var showClue = document.getElementById("clue");
getHint.onclick = function() {
var hints = ["Stoke Greeting","Saying Something is Easy", "Very Clumsy","delaying something for a minute", "When you are jealous of something","Something is frightening", "Earn Money", "Rough Exterior however has some potential", "When something rarely happens", "When you have succeeded/ getting yourself known by a company","accepting something , when you do not want to"];
showClue.innerHTML = "Clue: - " + hints [idx];
};
<button id="hint" name="hint" type="button">Hint</button>
<p id="clue">Clue: </p>
Sorted it- Thank you for all your help :)
I changed it current word from being a variable and now it works

HangMan Game-Replacing blanks w/ Letters

At this current moment I've been trying to work through an issue I've had with my Hangman JS game. I've spent the last week attempting to replace "underscores", which I have as placeholders for the current secret word. My idea was to loop through the correctLettersOUT, and wherever that particular letter exists in the placeholder would replace it with said letter. This small part of my code below is where the issue is I believe, but I have also created a function in my whole code if a new function necessary.
Any advice is appreciated.
function startGame() {
var testWord = document.getElementById("randTest").innerHTML = secretWord;
var correctLettersOUT = "";
document.getElementById("currentGuess").innerHTML = secretBlanks(secretWord)
function secretBlanks(secretWord) {
for (var i = 0; i < secretWord.length; i++) {
correctLettersOUT += ("_ ");
}
return correctLettersOUT;
}
}
The snippet of my JS is below, it may be large but all of it is necessary. If you wish to view the whole code in it's entirety, the link is CodePen Link.
var guessWords = ["school", "test", "quiz", "pencil", "ruler", "protractor", "teacher", "homework", "science", "math", "english", "history", "language", "elective", "bully", "grades", "recess", ];
var secretWord = guessWords[Math.floor(Math.random() * guessWords.length)];
var wrongLetters = [];
var correctLetters = [];
var repeatLetters = [];
var guesses = Math.round((secretWord.length) + (.5 * secretWord.length));
var correctLettersOUT = "";
function startGame() {
var testWord = document.getElementById("randTest").innerHTML = secretWord;
var correctLettersOUT = "";
document.getElementById("currentGuess").innerHTML = secretBlanks(secretWord)
function secretBlanks(secretWord) {
for (var i = 0; i < secretWord.length; i++) {
correctLettersOUT += ("_ ");
}
return correctLettersOUT;
}
}
function correctWord() {
var guessLetter = document.getElementById("guessLetter").value;
document.getElementById("letter").innerHTML = guessLetter;
for (var i = 0; i < secretWord.length; i++) {
if (correctLetters.indexOf(guessLetter) === -1)
{
if (guessLetter === secretWord[i]) {
console.log(guessLetter === secretWord[i]);
correctLettersOUT[i] = guessLetter;
correctLetters.push(guessLetter);
break;
}}
}
if (wrongLetters.indexOf(guessLetter) === -1 && correctLetters.indexOf(guessLetter) === -1) {
wrongLetters.push(guessLetter);
}
console.log(correctLetters); //Used to see if the letters were added to the correct array**
console.log(wrongLetters);
wordGuess();
}
function wordGuess() {
if (guessLetter.value === '') {
alert("You didn't guess anything.");
} else if (guesses > 1) {
// Counts down.
guesses--;
console.log('Guesses Left: ' + guesses);
// Resets the input to a blank value.
let guessLetter = document.getElementById('guessLetter');
guessLetter.value = '';
} else {
console.log('Game Over');
}
//console.log(guesses)
}
function replWord() { }
One solution to see if the word has been guessed completely and create the partially guessed display with the same info, is to keep a Set with the not yet guessed letters, initialized at game start unGuessed = new Set(secretWord);
Since the Set's delete method returns true if the letter was actually removed (and thus existed), it can be used as a check if a correct letter was entered.
Subsequently, the display can be altered in a single place (on startup and after guessing), by mapping the letters of the word and checking if the letter is already guessed:
function alterDisplay(){
document.getElementById("currentGuess").innerHTML =
[...secretWord].map(c=>unGuessed.has(c) ? '_' : c).join(' ');
}
Some mockup code:
let guessWords = ["school", "test", "quiz", "pencil", "ruler", "protractor", "teacher", "homework", "science", "math", "english", "history", "language", "elective", "bully", "grades", "recess", ],
secretWord, unGuessed, guesses;
function startGame() {
secretWord = guessWords[Math.floor(Math.random() * guessWords.length)];
guesses = Math.round(1.5 * secretWord.length);
unGuessed = new Set(secretWord);
setStatus('');
alterDisplay();
}
function alterDisplay(){
document.getElementById("currentGuess").innerHTML = [...secretWord].map(c=>unGuessed.has(c) ? '_' : c).join(' ');
}
function setStatus(txt){
document.getElementById("status").innerHTML = txt;
}
function correctWord() {
let c= guessLetter.value[0];
guessLetter.value = '';
if (!c) {
setStatus("You didn't guess anything.");
}
else if(unGuessed.delete(c)){
alterDisplay();
if(!unGuessed.size) //if there are no unguessed letters left: the word is complete
setStatus('Yep, you guessed it');
}
else if(--guesses < 1){
setStatus('Game Over!');
}
else
setStatus('Guesses Left: ' + guesses);
}
startGame();
let gl = document.getElementById("guessLetter");
gl.onkeyup= correctWord; //for testing: bind to keyup
gl.value = secretWord[1];correctWord(); //for testing: try the 2nd letter on startup
<div id=currentGuess></div>
<input id=guessLetter><span id=letter></span>
<div id='status'></div>

Comparing array elements to character

I'm trying to write a simple javascript program to check if a letter is a vowel. The problem is the output is incorrect and should say that " a is a vowel."
Javascript:
function findvowel(letter1, vowels) {
var count = vowels.length;
for (var i = 0; i < count; i++) {
if (vowels[i] === letter1) {
var message1 = " is a vowel";
document.getElementById('exercise3').innerHTML = letter1 + message1;
} else {
var message2 = " is a consonant";
document.getElementById('exercise3').innerHTML = letter1 + message2;
}
}
}
HTML:
<script>
$(document).ready(function() {
findvowel("a",["a","e","i","o","u"]);
});
</script>
Output:
a is a consonant
Add break to your loop so it doesn't keep going.
function findvowel(letter1, vowels) {
var count = vowels.length;
for (var i = 0; i < count; i++) {
if (vowels[i] === letter1) {
var message1 = " is a vowel";
document.getElementById('exercise3').innerHTML = letter1 + message1;
break;
} else {
var message2 = " is a consonant";
document.getElementById('exercise3').innerHTML = letter1 + message2;
}
}
}
You can actually use return false; to stop your function right away when a vowel is matched, however in normal cases break will be used because there might be other codes going on after the loop.
BTW:
function findvowel(letter){
//thanks p.s.w.g for reminding me []
return letter+" is a "+(/[aeiou]/i.test(letter)?"vowel":"constant");
}
You're testing the vowel in the for-loop and updating the output every time. So the output will only display if the last vowel that was tested matched the input. Instead, you should break out of the for-loop if a vowel is found, and only display a failure (" is a consonant") after you've tested all the vowels and you weren't able to find a match:
var count = vowels.length;
for (var i = 0; i < count; i++) {
if (vowels[i] === letter1) {
var message1 = " is a vowel";
document.getElementById('exercise3').innerHTML = letter1 + message1;
return;
}
}
var message2 = " is a consonant";
document.getElementById('exercise3').innerHTML = letter1 + message2;
But this method could be simplified to:
function findvowel(letter1) {
var isVowel = "aeiou".indexOf(letter1) > -1;
var message = letter1 + " is a " + (isVowel ? "vowel" : "consonant");
document.getElementById('exercise3').innerHTML = message;
}
This is what I would do, using native functions:
var letter = "a";
var isVowel = ["a","e","i","o","u"].some(function(vowel){
return vowel === letter;
});
Rergarding your message, I would try something like:
var message = letter + (isVowel ? " is a vowel" : " is a consonant");
I would pass in an object instead of an array and take advantage of the constant time lookup using the 'in' keyword. No need for a loop.
function findvowel(letter1, vowels) {
if (letter1 in vowels) {
var message1 = " is a vowel";
document.getElementById('exercise3').innerHTML = letter1 + message1;
} else {
var message2 = " is a consonant";
document.getElementById('exercise3').innerHTML = letter1 + message2;
}
}
then
var obj = {'a': true, 'e': true, 'i': true, 'o': true, 'u': true}
then call it
findvowel('a', obj)
Since you're already using jQuery, which offers $.inArray(), why don't you do this?
var vowels = ["a", "e", "i", "o", "u"];
$(document).ready(function() {
var letter = 'u';
var found = $.inArray(letter, vowels) > -1;
if(found) {
console.log(letter + ' is a vowel');
} else {
console.log(letter + ' is a consonant');
}
});

Javascript Functions, Uncaught syntax error, Unexpected token?

The following code is giving me an error in the chrome developer tools:
"uncaught syntax error- unexpected token"
Specifically, the Errors come up in the populate header function at
var notraw = JSON.parse(arrayraw)
and in the first if statement, at
parsed = JSON.parse(retrieved); //var test is now re-loaded!
These errors haven't come up in previous iterations. Does anyone know why?
// This statement should be ran on load, to populate the table
// if Statement to see whether to retrieve or create new
if (localStorage.getItem("Recipe") === null) { // if there was no array found
console.log("There was no array found. Setting new array...");
//Blank Unpopulated array
var blank = [
["Untitled Recipe", 0, 0]
];
// Insert Array into local storage
localStorage.setItem("Recipe", JSON.stringify(blank));
console.log(blank[0]);
} else {
console.log("The Item was retrieved from local storage.");
var retrieved = localStorage.getItem("Recipe"); // Retrieve the item from storage
// test is the storage entry name
parsed = JSON.parse(retrieved); //var test is now re-loaded!
// we had to parse it from json
console.log(parsed)
}
// delete from array and update
function deletefromarray(id) {
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
console.log(notraw[id])
notraw.splice(id, 1);
localStorage.setItem("Recipe", JSON.stringify(notraw));
}
// This adds to local array, and then updates that array.
function addtoarray(ingredient, amount, unit) {
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
notraw.push([ingredient, amount, unit]);
localStorage.setItem("Recipe", JSON.stringify(notraw));
var recipeid = notraw.length - 1
console.log("recipe id:" + recipeid)
}
//The calculation function, that gets the ingredients from the array, and calculates what ingredients are needed
function calculate(multiplier) {
alert("Calculate function was called")
var length = recipearray.length - 1;
console.log("There are " + length + " ingredients.");
for (i = 0; i < length; i++) {
console.log("raw = " + recipearray[i + 1][1] + recipearray[i + 1][2]);
console.log("multiplied = " + recipearray[i + 1][1] / recipearray[0][2] * multiplier + recipearray[i + 1][2]);
}
}
// The save function, This asks the user to input the name and how many people the recipe serves. This information is later passed onto the array.
function save() {
var verified = true;
while (verified) {
var name = prompt("What's the name of the recipe?")
var serves = prompt("How many people does it serve?")
if (serves === "" || name === "" || isNaN(serves) === true || serves === "null") {
alert("You have to enter a name, followed by the number of people it serves. Try again.")
verified = false;
} else {
alert("sucess!");
var element = document.getElementById("header");
element.innerHTML = name;
var header2 = document.getElementById("details");
header2.innerHTML = "Serves " + serves + " people"
calculate(serves)
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
notraw.splice(0, 1, [name, serves, notraw.length])
localStorage.setItem("Recipe", JSON.stringify(notraw))
return;
}
}
}
// the recipe function processes the inputs for the different ingredients and amounts.
function recipe() {
// Declare all variables
var ingredient = document.getElementById("ingredient").value;
var amount = document.getElementById("number").value;
var unit = document.getElementById("unit").value;
var count = "Nothing";
console.log("Processing");
if (isNaN(amount)) {
alert("You have to enter a number in the amount field")
} else if (ingredient === "" || amount === "" || unit === "Select Unit") {
alert("You must fill in all fields.")
} else if (isNaN(ingredient) === false) {
alert("You must enter an ingredient NAME.")
} else {
console.log("hey!")
// console.log(recipearray[1][2] + recipearray[1][1])
var totalamount = amount + unit
edit(ingredient, amount, unit, false)
insRow(ingredient, totalamount) // post(0,*123456*,"Fish")
}
}
function deleteRow(specified) {
// Get the row that the delete button was clicked in, and delete it.
var inside = specified.parentNode.parentNode.rowIndex;
document.getElementById('table').deleteRow(inside);
var rowid = inside + 1 // account for the first one being 0
console.log("An ingredient was deleted by the user: " + rowid);
// Remove this from the array.
deletefromarray(-rowid);
}
function insRow(first, second) {
//var first = document.getElementById('string1').value;
//var second = document.getElementById('string2').value;
// This console.log("insRow: " + first)
// Thisconsole.log("insRow: " + second)
var x = document.getElementById('table').insertRow(0);
var y = x.insertCell(0);
var z = x.insertCell(1);
var a = x.insertCell(2);
y.innerHTML = first;
z.innerHTML = second;
a.innerHTML = '<input type="button" onclick="deleteRow(this)" value="Delete">';
}
function populateheader() {
// Populate the top fields with the name and how many it serves
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
var element = document.getElementById("header");
element.innerHTML = notraw[0][0];
var header2 = document.getElementById("details");
// if statement ensures the header doesn't say '0' people, instead says no people
if (notraw[0][1] === 0) {
header2.innerHTML = "Serves no people"
} else {
header2.innerHTML = "Serves " + notraw[0][1] + " people"
}
console.log("Now populating Header, The Title was: " + notraw[0][0] + " And it served: " + notraw[0][1]);
}
function populatetable() {
console.log("Now populating the table")
// Here we're gonna populate the table with data that was in the loaded array.
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
if (notraw.length === 0 || notraw.length === 1) {
console.log("Array was empty.")
} else {
var count = 1;
while (count < notraw.length) {
amount = notraw[count][1] + " " + notraw[count][2]
insRow(notraw[count][0], amount)
console.log("Inserted Ingredient: " + notraw[count][0] + notraw[count][1])
count++;
}
}
}

Categories

Resources