Javascript Loop - can't figure this one out - javascript

I've tried everything that crossed my mind, but no luck with this loop (although i'm pretty new to javascript).
Prompt should ask a question until nothing entered. At that point all the 'results' that were previously entered should be taken and processed.
Result should look like (if entered for 1st prompt: 'CS A 4', 2nd 'BB B 3', 3rd 'CC C 3'..):....showing only after there was not entry for nth prompt
COURSE GRADE HOURS
CS A 4
BB B 3
CC C 3
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>gpa.html</title>
</head>
<script type="text/javascript">
function getData(){
var input=0,
results=[];
while(input!==""){input = prompt("Enter course name, grade and credit hours (e.g., 'CS3520 A 4' or click OK with no data to terminate.");
input = input.split(" ");
if(input==""){
results.push({
course: input[0].trim(),
grade: input[1].trim(),
creditHours: parseInt(input[2], 10)
});}}
return results;
}
var app = function() {
var result, results,
COLUMN_SEPARATOR = "\t\t";
document.writeln("<pre>");
results = getData();
document.writeln("COURSE" + COLUMN_SEPARATOR + "GRADE" + COLUMN_SEPARATOR + "HOURS");
for (var i = 0, j = results.length; i < j; i++) {
result = results[i];
document.writeln(result.course + COLUMN_SEPARATOR + result.grade + COLUMN_SEPARATOR + result.creditHours);
}
document.writeln();
computeGPA(results);
document.writeln("</pre>");
}
window.onload = app;
</script>
<body>
</body>
</html>

Removed (below the split): if(input=="")
Added (above the split): if (input === "") { break; }
This should do it:
function getData() {
var input = 0,
results = [];
while (input !== "") {
input = prompt("Enter course name, grade and credit hours (e.g., 'CS3520 A 4' or click OK with no data to terminate.");
if (input === "") { break; }
input = input.split(" ");
results.push({
course: input[0].trim(),
grade: input[1].trim(),
creditHours: parseInt(input[2], 10)
});
}
return results;
}
var app = function () {
var result, results,
COLUMN_SEPARATOR = "\t\t";
document.writeln("<pre>");
results = getData();
document.writeln("COURSE" + COLUMN_SEPARATOR + "GRADE" + COLUMN_SEPARATOR + "HOURS");
for (var i = 0, j = results.length; i < j; i++) {
result = results[i];
document.writeln(result.course + COLUMN_SEPARATOR + result.grade + COLUMN_SEPARATOR + result.creditHours);
}
document.writeln();
document.writeln("</pre>");
}
But i think that this would be an even better solution:
function getData() {
var input = true,
results = [];
while (input) {
input = prompt("Enter course name, grade and credit hours (e.g., 'CS3520 A 4' or click OK with no data to terminate.");
if (!input) { break; }
input = input.split(" ");
results.push({
course: input[0].trim(),
grade: input[1].trim(),
creditHours: parseInt(input[2], 10)
});
}
return results;
}
var app = function () {
var result, results,
COLUMN_SEPARATOR = "\t\t";
document.writeln("<pre>");
results = getData();
document.writeln("COURSE" + COLUMN_SEPARATOR + "GRADE" + COLUMN_SEPARATOR + "HOURS");
for (var i = 0, j = results.length; i < j; i++) {
result = results[i];
document.writeln(result.course + COLUMN_SEPARATOR + result.grade + COLUMN_SEPARATOR + result.creditHours);
}
document.writeln();
document.writeln("</pre>");
}
Because the return value of canceled prompt() depends on the browser. In most browsers the return value is null. However, some very old browsers (e.g. early versions of IE) used to return '' (an empty string).
So instead of using something like if (input != '' && input != null), just use true or false.
User pressed OK, but the input field was empty input === ""
User typed something and hit OK (or enter) input == true
User pressed CANCEL input == null or input == ""
UPDATE
About the textarea thing, try something like this (i didn't test it):
textareaContentByLines = textareaContent.split("\n");
for(index = 0; index < textareaContentByLines.length; index++){
input = textareaContentByLines.split(" ");
results.push({
course: textareaContentByLines[index][0].trim(),
grade: textareaContentByLines[index][1].trim(),
creditHours: parseInt(textareaContentByLines[index][2], 10)
});
}

Related

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

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.

Split String into dictionary words and non-dictionary words

I want to split a string into a sequence of words using a dictionary.
The following function only gives me words with letter boundaries.
function spltToWord(prm){
var spltedAr = prm.split(/(?=[A-Z][a-z])/);
return spltedAr.join(" ").trim();
}
I want to separate the text into dictionary/non-dictionary words.
For example:
Iamno123prisoner - I am no 123 prisoner
USAisveryrich - USA is very rich
Albertgaveme5rupees - Albert gave me 5 rupees
A sample dictionary can be found Here for refrence.
If the dictionary contains many words, you'll want a faster solution than matching one word at a time against substrings of the input text. If there are ten thousand words in the dictionary, you have to do at least ten thousand character comparisons with this naive approach.
A more efficient solution involves the use of a trie in which you've stored the dictionary words. Checking whether a word is in the dictionary requires only a single pass through the string.
Another advantage is that you can search for the longest match starting from a given position in the text. This approach is demonstrated in the following snippet, which includes a small dictionary that suffices to process your examples. You can replace this with your own dictionary when you run the code locally.
var Global = {
dictionary: [
'aa', 'I', 'i', 's',
'aah', 'am',
'aahed', 'no',
'aahing', '123',
'aahs', 'prisoner',
'aal', 'USA',
'aalii', 'is',
'aaliis', 'very',
'aals', 'rich',
'aardvark', 'Albert',
'aardvarks', 'gave', 'me', '5', 'rupees'
]
};
function addToTrie(word) {
var node = Global.trie;
for (var pos = 0; pos < word.length; ++pos) {
var letter = word.charAt(pos);
if (node[letter] === undefined) {
node[letter] = {};
}
node = node[letter];
}
node.terminal = true;
}
function findLongestMatch(text, start) {
var node = Global.trie,
best = start - 1;
for (var pos = start; pos < text.length; ++pos) {
var letter = text.charAt(pos);
if (node[letter] === undefined) {
break;
}
node = node[letter];
if (node.terminal) {
best = pos;
}
}
return best - start + 1;
}
function loadTrie() {
var words = Global.dictionary,
trie = Global.trie = {};
words.forEach(function (word) {
addToTrie(word);
});
};
function println(label, s, labelStyle) {
if (s === undefined) {
s = label || '';
} else {
var className = 'label' + (labelStyle ? ' ' + labelStyle : '');
s = '<div class="' + className + '">' + label + '</div> ' + s;
}
document.getElementById('message').innerHTML += (s + '<br />');
}
function process(text) {
var results = [],
letters = [],
pos = 0;
while (pos < text.length) {
var length = findLongestMatch(text, pos);
if (length == 0) {
letters.push(text.charAt(pos));
pos += 1;
} else {
if (letters.length != 0) {
results.push({ word: letters.join(''), known: false });
letters = [];
}
results.push({ word: text.substring(pos, pos + length), known: true });
pos += length;
}
}
if (letters.length != 0) {
results.push({ word: letters.join(''), known: false });
letters = [];
}
var breakdown = results.map(function (result) {
return result.word;
});
println();
println(' breakdown:', '/' + breakdown.join('/') + '/');
results.forEach(function (result) {
println((result.known ? 'in dictionary' : ' unknown') + ':',
'"' + result.word + '"', (result.known ? undefined : 'unknown'));
});
};
window.onload = function () {
loadTrie();
process('WellIamno123prisoner');
process('TheUSAisveryrichman');
process('Albertgaveme5rupeesyo');
};
body {
font-family: monospace;
color: #444;
font-size: 14px;
line-height: 20px;
}
.label {
display: inline-block;
width: 200px;
font-size: 13px;
color: #aaa;
text-align: right;
}
.label.unknown {
color: #c61c39;
}
<div id="message"></div>
Edit #2
var words = ["apple", "banana", "candy", "cookie", "doughnut"];
var input = "banana123candynotawordcookieblahdoughnut";
var currentWord = "",
result = "";
while (true) {
for (var i = 0; i < input.length; i++) {
currentWord += input[i];
if (words.indexOf(currentWord) >= 0) {
result += " " + currentWord + " ";
currentWord = "";
}
}
if (currentWord.length > 0) {
result += currentWord[0];
input = currentWord.substr(1);
currentWord = "";
} else {
break;
}
}
console.log(result.trim()); // "banana 123 candy notaword cookie blah doughnut"
Note the result will contain two spaces if there are two consecutive dictionary words. You can fix this using regex.
It isn't the prettiest solution (you can make it recursive which may be more readable), and it doesn't provide multiple solutions (see DP link in comment for that).
Edit this doesn't take into account non-dictionary words.
Using a simple greedy algorithm:
var words = ["apple", "banana", "candy", "cookie", "doughnut"];
var input = "bananacandycookiedoughnut";
var currentWord = "", result = "";
for (var i = 0; i < input.length; i++) {
currentWord += input[i];
if (words.indexOf(currentWord) >= 0) {
result += currentWord + " ";
currentWord = "";
}
}
console.log(result.trim()); // "banana candy cookie donught"
Of course you would want to modify various part of this, e.g. use a set for the dictionary and take into account case [in]sensitivity.

JSON return value to global variable

Simply my code looks like this:
var thevariable = 0;
For(){
//somecode using thevariable
$.getJSON('',{},function(e){
//success and i want to set the returned value from php to my variable to use it in the forloop
thevariable = e.result;
});
}
my main problem that the variable value stays "0", during the whole For loop, while i only want it to be "0" at the first loop, then it takes the result returned from PHP to use it on for loop.
here it my real code if you need to take a look:
var orderinvoice = 0;
for(var i=0; i<table.rows.length; i++){
var ordername = table.rows[i].cells[5].innerText;
var orderqty = ((table.rows[i].cells[1].innerText).replace(/\,/g,'')).replace(/Qty /g,'');
var orderprice = (table.rows[i].cells[2].innerText).replace(/\$/g,'');
var ordertype = table.rows[i].cells[3].innerText;
var orderlink = table.rows[i].cells[4].innerText;
$.getJSON('orderprocess.php', {'invoice': orderinvoice, 'pay_email': email, 'ord_name': ordername, 'ord_qty': orderqty, 'ord_price': orderprice, 'ord_type': ordertype, 'ord_link': orderlink}, function(e) {
console.log();
document.getElementById("result").innerText= document.getElementById("result").innerText + "Order #"+e.result+" Created Successfully ";
document.getElementById("invoker").innerText = ""+e.invoice;
orderinvoice = e.invoice;
if(i+1 == table.rows.length){
document.getElementById("result").innerText= document.getElementById("result").innerText + "With invoice #" + e.invoice;
}
});
in a loop block, before one ajax complete other one will be run and this's javascript natural treatment. For your case you can call a function at the end of success event. Do something like this:
var i = 0;
doSt();
function doSt() {
var orderinvoice = 0;
var ordername = table.rows[i].cells[5].innerText;
var orderqty = ((table.rows[i].cells[1].innerText).replace(/\,/g, '')).replace(/Qty /g, '');
var orderprice = (table.rows[i].cells[2].innerText).replace(/\$/g, '');
var ordertype = table.rows[i].cells[3].innerText;
var orderlink = table.rows[i].cells[4].innerText;
$.getJSON('orderprocess.php', { 'invoice': orderinvoice, 'pay_email': email, 'ord_name': ordername, 'ord_qty': orderqty, 'ord_price': orderprice, 'ord_type': ordertype, 'ord_link': orderlink }, function(e) {
console.log();
document.getElementById("result").innerText = document.getElementById("result").innerText + "Order #" + e.result + " Created Successfully ";
document.getElementById("invoker").innerText = "" + e.invoice;
orderinvoice = e.invoice;
if (i + 1 == table.rows.length) {
document.getElementById("result").innerText = document.getElementById("result").innerText + "With invoice #" + e.invoice;
}
i++;
if (i < table.rows.length) doSt();
});
}
I think you need a recursive function that always deals with the first element in your rows array and then splices it off and calls itself. For example, something like this:
function getStuff(rows, results) {
if (rows.length > 0) {
var ordername = rows[0].cells[5].innerText;
$.getJSON('orderprocess.php', { 'ord_name': ordername }, function (e) {
// do some stuff
results.push('aggregate some things here?');
rows.splice(0, 1);
return getStuff(rows, results);
});
} else {
return results;
}
}
When the array is spent, results will be returned with whatever aggregate you wanted at the end of the cycle. Then, you can do as you please with the results. I think you can also manipulate the DOM inside the function as you see fit if that makes more sense. Hope this helps.

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