Why are null values inserted into the table? - javascript

I am trying to insert name and age into the HTML table using a prompt. But it inserts null values in the result, Can you implement a solution for this? Thank you in advance!
var i = 0;
var n = new Array();
var a = new Array();
var name = " ",
age = " ";
while (!(name == null || age == null)) {
name = prompt("Enter name: ");
age = prompt("Enter age: ");
n[i] = name;
a[i] = age;
i++;
}
document.writeln("<table border='1' width='25%'>");
document.writeln("<caption>Arrays</caption>");
document.writeln("<th>Name</th><th>Age</th>");
for (var k in n) {
if (!(k == null))
document.writeln("<tr><td>" + n[k] + "</td><td>" + a[k] + "</td></tr>");
}
document.write("</table>");
<h2>JavaScript Arrays</h2>
<p>JavaScript array elements are accesses using numeric indexes (starting from 0).</p>
<p id="demo"></p>

That's because you are checking the null values before the prompt. Use the condition after name or age is provided.
while(true){
name=prompt("Enter name: ");
age=prompt("Enter age: ");
if(name==null || age==null) break;
n[i]=name;
a[i]=age;
i++;
}

The prompt function returns null on Cancel/Esc.
This is explained in the MDN documentation of prompt. To avoid printing null in your html table, you need to print it only if it exists.
Here is your code with the right condition:
var i = 0;
var n = new Array();
var a = new Array();
var name = " ",
age = " ";
while (!(name == null || age == null)) {
name = prompt("Enter name: ");
age = prompt("Enter age: ");
n[i] = name;
a[i] = age;
i++;
}
document.writeln("<table border='1' width='25%'>");
document.writeln("<caption>Arrays</caption>");
document.writeln("<th>Name</th><th>Age</th>");
for (var k in n) {
if(n[k] !== null && a[k] !== null)
document.writeln("<tr><td>" + n[k] + "</td><td>" + a[k] + "</td></tr>");
}
document.write("</table>");
<h2>JavaScript Arrays</h2>
<p>JavaScript array elements are accesses using numeric indexes (starting from 0).</p>
<p id="demo"></p>

Related

Assigning instances to my array (javascript). Whats causing this error?

I need to assign instances of my object as values in my array, but when I try to add let to my loop for collecting user input, I get an error stating that "[" is an unexpected token. This is a new technique to me so I'm not sure if this is even a practical method for making a table. Any help is appreciated.
<script>
function generateTable() {
var tblStart = "<table>";
//This is the header line for my table.
var tblMeat = "<tr> <td><b>Name</b></td> <td><b>Attendance</b></td> <td><b>Homework</b></td> <td><b>Midterm</b></td> <td><b>Final</b></td> <td><b>Course Grade</b></td> <td><b>Round Grade</b></td> <td><b>Letter Grade</b></td> </tr>";
var tblStop = "</table>";
//This determines the number of rows.
var rowCount = prompt("How many students are in the class?");
//I want to assign instances of Student to this array which will be used to fill the table cells.
var pupil = [NUMBER(rowCount)];
//This object should process user entries and use them to calculate the total grade, rounded grade, and letter grade.
function Student(name, attendance, homework, mGrade, fGrade) {
this.name = name;
this.attend = attendance;
this.homewrk = homework;
this.midter = mGrade;
this.fingrad = fGrade;
this.course = function () {
var attGrade = this.attend * 0.1;
var hwkGrade = this.homewrk * 0.2;
var midGrade = this.midter * 0.3;
var finGrade = this.fingrad * 0.4;
var combGrade = attGrade + hwkGrade + midGrade + finGrade;
return combGrade.toFixed(2);
};
this.round = Math.round(this.course);
this.letter = function() {
if(this.course < 60) {
return '<p style="color:red;">F</p>';
} else if(this.course >= 60 && this.course <= 69.9){
return "D";
} else if(this.course >= 70 && this.course <= 79.9) {
return "C";
} else if(this.course >= 80 && this.course <= 89.9) {
return "B";
} else if(this.course >= 90 && this.course <= 100) {
return "A";
};
};
}
/*This loop should collect user input based on the declared number of students, and assign input values to instances of
Student based on which execution of the loop is being run. I am getting an error stating "[" is unexpected for line 79.
*/
for (var r = 0; r < rowCount; r++) {
var studentN = prompt("Enter student name.");
var studentA = prompt("Enter student attendance.");
var studentH = prompt("Enter student homework grade.");
var studentM = prompt("Enter student midterm grade.");
var studentF = prompt("Enter student final grade.");
let pupil[r] = new Student(studentN, studentA, studentH, studentM, studentF);
}
for(var i = 0; i < rowCount; i++) {
tblMeat += "<tr>";
for(var j = 0; j < 8; j++) {
tblMeat += "<td>" + pupil[i].name + "</td><td>" + pupil[i].attend + "</td><td>" + pupil[i].homewrk + "</td><td>" + pupil[i].midter + "</td><td>" + pupil[i].fingrad + "</td><td>" + pupil[i].course() + "</td><td>" + pupil[i].round + "</td><td>" + pupil[i].letter() + "</td>";
}
tblMeat += "</tr>";
}
//This just puts it all together.
var completeTable = tblStart + tblMeat + tblStop;
document.getElementById("placetable").innerHTML = completeTable;
}
</script>
I ran your program through uglifyJS. It's actually for compressing javascript code, but when there is a lot of code to debug, it's a life changer.
The script told me:
Parse error: Unexpected token: punc ([)
Line 59, column 16
let pupil[r] = new Student(studentN, studentA, studentH, studentM, studentF);
You're trying to define an already existing variable. Remove "let".
A tiny advice for the future.

Issue with evaluating average of an array

I am trying to display an array of test scores and above them, the average of those scores. Here is the code I am using:
var clickDisplayResults = function () {
$("results").value = "";
function calculate(scores) {
var i = 0, sum = 0, len = scores.length;
while (i < len) {
sum = sum + scores[i++];
};
return sum / len;
};
var average = calculate(scores);
$("results").value = "The average score is: " + parseInt(average) + "\n";
$("results").value += "High Score: " + Math.max.apply(null, scores) + "\n";
$("results").value += "Low Score: " + Math.min.apply(null, scores) + "\n" + "\n";
for (var i = 0; i < names.length; i++) {
$("results").value += names[i] + ", " + scores[i] + "\n";
};
When I do this, however, I get an average in a ridiculous range after adding a new score.
Here is the add score code:
var clickAddScore = function () {
if ( $("name").value == "" || $("score").value < 0 || $("score").value > 100 || isNaN($("score").value) ) {
alert("Please enter a valid name and score");
$("name").value = "";
$("score").value = "";
return false;
};
else {
names[names.length] = $("name").value;
scores[scores.length] = $("score").value;
$("name").value = "";
$("score").value = "";
};
};
Any advice would be appreciated.
You are working with a string and treating it like a number
console.log("100" + 100);
You need to convert the string to a number. You can use parseInt, parseFloat, Number, or Unary plus.
Your code is a bit inefficient since you keep accessing the DOM for the value so declare some variables. And your else statement was wrong.
var clickAddScore = function() {
var studentName = $("name").value.trim();
var score = Number($("score").value);
if (studentName == "" || score < 0 || score > 100 || isNaN(score)) {
alert("Please enter a valid name and score");
} else {
names.push(studentName);
scores.push(score);
}
$("name").value = "";
$("score").value = "";
}

Printing an object within an array showing as blank

function displayEvent(array) {
var vOutput = "";
var ind = 0;
for(var i = 0; i < array.length; i++) {
ind += 1;
vOutput += "Name " + ind + ": " + array[i].name + ", Age " + array[i].age + "<br />";
}
document.getElementById("output").innerHTML = vOutput;
}
function init() {
var arrEvent = [];
var objEvent = {};
objEvent.name = prompt("Enter name of Event");
objEvent.age = prompt("Enter number of Guests");
arrEvent.push(objEvent);
while(objEvent.name.length > 0) {
objEvent.name = prompt("Enter name of Event");
objEvent.age = prompt("Enter number of Guests");
if(objEvent.name.length > 0) {
arrEvent.push(objEvent);
}
}
displayEvent(arrEvent);
}
window.onload = init;
Trying to print an object array into the HTML paragraph id and whenever I execute the code above I get the correct output but the array elements just show as blank.
You are always pushing the same object into your array.
Change to:
function displayEvent(array) {
var vOutput = "";
var ind = 0;
for(var i = 0; i < array.length; i++) {
ind += 1;
vOutput += "Name " + ind + ": " + array[i].name + ", Age " + array[i].age + "<br />";
}
document.getElementById("output").innerHTML = vOutput;
}
function init() {
var arrEvent = [];
var name = '';
var age = '';
name = prompt("Enter name of Event");
age = prompt("Enter number of Guests");
arrEvent.push({name: name, age: age});
while(name.length > 0) {
name = prompt("Enter name of Event");
age = prompt("Enter number of Guests");
if(name.length > 0) {
arrEvent.push({name: name, age: age});
}
}
displayEvent(arrEvent);
}
window.onload = init;

My for loop doesn't work [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I was trying to shorten the code for returning "NO ANSWER" when one of my prompts was left blank in the code below:
var name = prompt("What is your name?");
var age = prompt("What is your age?");
var address = prompt("What is your email address?");
var credit = prompt("What is your credit card number?");
var social = prompt("What is your social security number?");
var arr = [name, age, address, credit, social];
var l = arr.length;
for (var i = 0; i < l; i++) {
if (arr[i] == "") {
arr[i] = "NO ANSWER";
}
}
alert("Your information is " + name + ", " + age + ", " + address + ", " + credit + ", and" + social + ".");
alert("Now the internet has all of your information. Have a nice day >:D");
however, the code doesn´t work. can someone tell me why?
The for loop does work and works as expected. You need to use array arr while printing or using those input variables. That's because when you do arr[i] = "NO ANSWER";, you actually set the array element to "NO ANSWER", not the original variables. See the following:
var name = prompt("What is your name?");
var age = prompt("What is your age?");
var address = prompt("What is your email address?");
var credit = prompt("What is your credit card number?");
var social = prompt("What is your social security number?");
var arr = [name, age, address, credit, social];
var l = arr.length;
for (var i = 0; i < l; i++) {
if (arr[i] == "") {
arr[i] = "NO ANSWER";
}
}
alert("Your information is " + arr[0] + ", " + arr[1] + ", " + arr[2] + ", " + arr[3] + ", and" + arr[4] + ".");
alert("Now the internet has all of your information. Have a nice day >:D");
Try this instead. It seems that you are updating arr but you are not printing arr to the screen.
var name = prompt("What is your name?");
var age = prompt("What is your age?");
var address = prompt("What is your email address?");
var credit = prompt("What is your credit card number?");
var social = prompt("What is your social security number?");
var arr = [name, age, address, credit, social];
var l = arr.length;
for (var i = 0; i < l; i++) {
if (arr[i] == "") {
arr[i] = "NO ANSWER";
}
}
alert("Your information is " + arr[0] + ", " + arr[1] + ", " + arr[2] + ", " + arr[3] + ", and " + arr[4] + ".");
I tried dry running the code with no address. following code works. The if statement need to change
testarr = function () {
var name = 'xxx';
var age = 10;
var address;
var credit = 252525;
var social = 564654;
var arr = [name, age, address, credit, social];
var l = arr.length;
for (var i = 0; i < l; i++) {
if (!arr[i]) {
arr[i] = "NO ANSWER";
}
}
return arr;
//alert("Your information is " + name + ", " + age + ", " + address + ", " + credit + ", and" + social + ".");
//alert("Now the internet has all of your information. Have a nice day >:D");
}
var t = new testarr();
console.log ("Your information is " + t[0] + ", " + t[1] + ", " + t[2] + ", " + t[3] + ", and" + t[4] + ".")

how to check if an input is a number in js

here is the code I've been working on.
var storeUsersInfo = [];
var amountOfUsers = prompt("How many users do you want?");
amountOfUsers = parseInt(amountOfUsers);
function returnUserInput() {
var askFirstName = prompt("What is your first name?");
var askLastName = prompt("What is your last name" + " " + titleCase(askFirstName) + "?");
var askAge = prompt("How old are you" + " " + titleCase(askFirstName) + " " + titleCase(askLastName) + "?");
if(askAge != int) {
alert("Not a valid input")
};
return {
firstName: titleCase(askFirstName),
lastName: titleCase(askLastName),
age: askAge
};
};
function titleCase(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
};
for(var i = 0; i < amountOfUsers; i++) {
storeUsersInfo[i] = returnUserInput();
}
console.log(storeUsersInfo);
I wondering how I can check the input of askAge to see if it equals a number.
I tried some code as you can see on lines 9-12 and I can't figure it out. I know it has to do something with typeof.
Thoughts?
multiply it by 1 and if it returns NaN and is not the same as the original input- its not a number
var askAge = prompt("How old are you" + " " + titleCase(askFirstName) + " " + titleCase(askLastName) + "?");
var askedAge=parseInt(askAge)*1;
if(askedAge != askAge) {
alert("Not a valid input");
}
This can be solved using a combination of Number.isInteger and Number.parseInt. Both of which have been standardized in ES2015.
The following expression will check if the age is valid:
Number.isInteger(Number.parseInt(askAge));
Note that you'll have to parse the user input to an integer first; this can either result in a valid integer or in NaN.
If it is an integer, then Number.isInteger will make the expression true; otherwise, the parsed number was NaN and the expression will become false.
I think you can you this code,
function isNumeric(x) {
return !isNaN(parseFloat(x)) && isFinite(x);
}
You could use
Number.isInteger(askAge)
Reference :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
try this
var check = /^[0-9]+$/;
var checkall = askAge.match(check);
if (!checkall){
alert("Not a valid input")
}
The cryptic answer:
var askAge = prompt("How old are you" + " " + titleCase(askFirstName) + " " + titleCase(askLastName) + "?");
if(!Number.isInteger(Number.parseInt(askAge))) {
alert("Not a valid input")
};
More:
You are partially correct in your assumption, you do have to check the type of the number to ensure that is is a number and also that it is an integer. How you actually DO that has several options. Here is one that should work.
You must determine if you wish to use Number() or Number.parseInt() as that determination will herein make a difference in the accepted values.
Given that, I choose to use the parseInt in this answer. I also constructed it to not accept 0 as a value for the number of users.
First we use or create the isInteger and parseInt in Number:
Number.isInteger = Number.isInteger || function(value) {
return typeof value === "number" && isFinite(value) && Math.floor(value) === value;
};
Number.parseInt = Number.parseInt || parseInt;
Declare our other functions: (commented)
// this will error out if "Cancel" on the prompt is clicked (null is passed in mystring)
function titleCase(mystring) {
return mystring.charAt(0).toUpperCase() + mystring.slice(1);
}
function returnUserInput() {
var isValid = false;
var askFirstName = "";
var askLastName = "";
var askAge = null;
do {
askFirstName = prompt("What is your first name?"); // currently accepts " " as a valid name
askLastName = prompt("What is your last name" + " " + titleCase(askFirstName) + "?"); // accepts " " as a valid name
askAge = prompt("How old are you" + " " + titleCase(askFirstName) + " " + titleCase(askLastName) + "?");
isValid = Number.isInteger(Number.parseInt(askAge));
if (!isValid) {
alert("Not a valid input");
}
} while (!isValid); // accepts 0 and negative values as age
return {
firstName: titleCase(askFirstName),
lastName: titleCase(askLastName),
age: Number.parseInt(askAge) // was using the unparsed string "4' if 4 was entered
};
}
Use the functions:
var storeUsersInfo = [];
var amountOfUsers = 0;
var enteredCount = 0;
do {
amountOfUsers = prompt("How many users do you want?");
enteredCount = Number.parseInt(amountOfUsers, 10);// parse it
} while (!(Number.isInteger(Number.parseInt(amountOfUsers, 10))) && !enteredCount > 0)
amountOfUsers = enteredCount;
for (var i = 0; i < amountOfUsers; i++) {
storeUsersInfo[i] = returnUserInput();
}
console.log(storeUsersInfo);// console.dir might also work (better?)

Categories