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

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.

Related

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 = "";
}

I cant solve this: to find the minimum number from an array that is input through prompt()

I cant solve this homework that needs to ask the user to enter student marks and output the minimum mark of the student, can someone please help me solve this problem:
<script>
function getMarks() {
var marks = prompt('Type the students marks, seperate each student mark with comma, do not write the percentage mark % .').split(',');
return marks;
}
var studentMarks = getMarks();
var arrayLength = studentMarks.length;
var studentNumber = 0;
var msg = '';
var i;
for (i = 0; i < arrayLength; i++) {
studentNumber = (i + 1);
msg += 'student ' + studentNumber + ': ';
msg += studentMarks[i] + '%' + '<br />';
} document.getElementById('marks').innerHTML = msg; document.getElementById('marke').innerHTML = math.min.apply(null, studentMarks) + '%';
</script>
I will do that in the following way:
function getMarks() {
var marks = prompt('Type the students marks, seperate each student mark with comma, do not write the percentage mark % .');
return marks.split(',').map(n => Number(n));
}
var marksArray = getMarks();
var studentMarks = Math.min(...marksArray);
var position = marksArray.indexOf(studentMarks);
var msg = 'Student ' + Number(position + 1) + ': ';
document.getElementById('marks').innerHTML = msg + studentMarks + '%';
<p id="marks"></p>

Using the Date Object in an Array with Javascript

I need to display a date from an array and it needs to be incremented for each input by 1 day. The date should display as mm/dd/yyyy. I was able to get the date to display correctly with the code that is in the message but after each input the all the dates would increment. I need just the last input to increment a day and I thought putting it in an array would work but now nothing displays. Thanks for helping.
var lowTempArray = [];
var highTempArray = [];
var nowArray = [];
function process() {
'use strict';
//declare variables
var lowTemp = document.getElementById('lowTemp');
var highTemp = document.getElementById('highTemp');
var output = document.getElementById('output');
var date = new Date();
var message = ' ';
if (lowTemp.value) {
lowTempArray.push(lowTemp.value);
if (highTemp.value) {
highTempArray.push(highTemp.value);
message = '<table><th>Date </th><th> Low Temperatures</th><th> High Temperatures</th>';
for (var i = 0, count = lowTempArray.length; i < count; i++) {
for (var i = 0, count = highTempArray.length; i < count; i++) {
for (var i = 0, count = nowArray.length; i < count; i++) {
nowArray.push(new Date(date.getTime()));
date.setDate(date.getDate() + count);
message += '<tr><td>' + ((nowArray.getMonth() + 1) + '/' + (nowArray.getDate() + count) + '/' + nowArray.getFullYear()) + '</td><td> ' + lowTempArray[i] + '</td><td> ' + highTempArray[i] + '</td></tr>';
}
message += '</table>';
output.innerHTML = message;
}
}
}
}
return false;
}
function init() {
'use strict';
document.getElementById('theForm').onsubmit = process;
} // End of init() function.
window.onload = init;

When using a for loop in Javascript, how can I display output in multiple columns?

The user should be able to enter in an integer and see the base, squared, and cubed result of that number. The base result should be listed under the "base" header, the squared result should be listed under the "squared" header and the cubed result should be listed under the "cubed" result. However, my output is listed all results under the "base" header. How can I make the results be listed under the related headers? This is what I have:
var $ = function (id) {
return document.getElementById(id);
}
var calculate = function () {
//Get the input from the user and assign it to the userInput variable
var integer = $("integer").value;
var header = "Base" + " " + "Square" + " " + "Cubed" + "\n";
var squared = "";
var cubed = "";
var base = "";
var displayOutput;
for (var i = 1; i <= integer; i++) {
base += i + "\n";
squared += i * i + "\n";
cubed += i * i * i + "\n";
displayOutput = base + squared + cubed;
}
$("output").value = header + displayOutput;
}
var form_reset = function () {
$("output").value = "";
$("integer").value = "";
}
//Assign event handlers to their events
window.onload = function () {
$("powers").onclick = calculate;
$("clear").onclick = form_reset;
}
It all depends on the output. Trying to stay as close as possible to your code, seems you are inserting your resulting displayOutput string into a textarea control. If you want to keep it that way, try tabs (\t) to separate your columns, and only a new line at the end (\n). Also, I noticed you were concatenating every column (base, square, and cubed) on every iteration, so I removed that. Here's the result:
var $ = function (id) {
return document.getElementById(id);
};
var calculate = function () {
//Get the input from the user and assign it to the userInput variable
var integer = $("integer").value;
var header = "Base" + " " + "Square" + " " + "Cubed" + "\n";
var squared = "";
var cubed = "";
var base = "";
var displayOutput = "";
for (var i = 1; i <= integer; i++) {
base = i + "\t";
squared = i * i + "\t";
cubed = i * i * i + "\n";
displayOutput += base + squared + cubed;
}
$("output").value = header + displayOutput;
};
var form_reset = function () {
$("output").value = "";
$("integer").value = "";
};
//Assign event handlers to their events
window.onload = function () {
$("powers").onclick = calculate;
$("clear").onclick = form_reset;
$("theform").onsubmit = function() { return false; };
};

Shuffle select menu options

Basically I have 5 words picked out of an array (English Words) And I pick 1 French word out of another array which the user then has to guess what that french word means in english.
At the moment I am adding the Correct English Answer to the end of the select menu because I don't know how to add it inbetween the others randomly, or more so to shuffle the select menus options
I Have added my JSfiddle below, It is an exact replica. You will realise that the bottom option is always correct! (The user will begin to know the pattern). I've also had to add my javascript below to be able to post the JSfiddle
http://jsfiddle.net/jamesw1/w8p7b6p3/5/
var
RanNumbers = new Array(6),
foreignWords = ['un', 'deux', 'trois', 'quatre', 'cinq', 'six', 'sept', 'huit', 'neuf', 'dix', 'onze', 'douze', 'treize', 'quatorze', 'quinze', 'seize', 'dix-sept', 'dix-huit', 'dix-neuf', 'vingt', 'vingt et un', 'vingt-deux', 'vingt-trois', 'vingt-quatre', 'vingt-cinq', 'vingt-six', 'vingt-sept', 'vingt-huit', 'vingt-neuf', 'trente'],
translate = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty', 'twenty-one', 'twenty-two', 'twenty-three', 'twenty-four', 'twenty-five', 'twenty-six', 'twenty-seven', 'twenty-eight', 'twenty-nine', 'thirty'],
number = Math.floor((Math.random() * 30)),
output = '',
correctAns = translate[number];
//Generate random numbers to pick the available answers
function wordGen() {
for (var h = 0; h < RanNumbers.length; h++) {
var temp = 0;
do {
temp = Math.floor(Math.random() * 30);
} while (RanNumbers.indexOf(temp) > -1);
RanNumbers[h] = temp;
}
}
//Call the previous function
wordGen();
//Create dynamic select menu
document.getElementById('generatedWord').textContent = foreignWords[number];
var guess = "<select name='guesses' id='guesses'>";
for (var i = 0; i < 6; i++) {
guess += "<option value='" + i + "'>" + translate[RanNumbers[i]] + "</option>";
}
guess += '<option value="6">' + correctAns + '</option>';
guess += "</select>";
document.getElementById('output').innerHTML = guess;
numGuessed = document.getElementById('guesses').value;
function arrayValueIndex(arr, val) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === val) {
return i;
}
}
return false;
}
var numGames = 5;
var numGuesses = 1;
var correct = 0;
var wrong = 0;
var prevNumber;
//On click, gather correct and wrong answers, create new numbers, create new options, create new word.
document.getElementById('submitAns').onclick = function () {
prevNumber = number;
number = Math.floor((Math.random() * 30)),
output = '',
correctAns = translate[number];
document.getElementById('numGuess').innerHTML = "Question #" + numGuesses;
var
genWord = document.getElementById('generatedWord').textContent,
select = document.getElementById('guesses'),
selectedText = select.options[select.selectedIndex].text;
prevNumber === arrayValueIndex(translate, selectedText) ? correct++ : wrong++;
//Re doing the function, getting new values...
function wordGen() {
for (var j = 0; j < RanNumbers.length; j++) {
var temp = 0;
do {
temp = Math.floor(Math.random() * 30);
} while (RanNumbers.indexOf(temp) > -1);
RanNumbers[j] = temp;
}
}
//Call the previous function
wordGen();
//Create dynamic select menu
document.getElementById('generatedWord').textContent = foreignWords[number];
var guess = "<select name='guesses' id='guesses'>";
for (var i = 1; i <= 6; i++) {
guess += "<option value='" + i + "'>" + translate[RanNumbers[i]] + "</option>";
}
guess += '<option value="6">' + correctAns + '</option>';
guess += "</select>";
document.getElementById('output').innerHTML = guess;
numGuessed = document.getElementById('guesses').value;
function arrayValueIndex(arr, val) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === val) {
return i;
}
}
return false;
}
//Checking of the answers below, Accumilating correct and wrong answer.
numGuesses++;
if (numGuesses == 6) {
document.getElementById('generatedWord').innerHTML = "<span style='font-size:12px;color:red';>Please click for a new game when ready!</span><br /><p>You got " + wrong + " questions wrong " + "<br />You got " + correct + " questions correct";
$('#submitAns').hide();
}
};
You should use Math.random method, it would be something like this:
var correctAnswerIndex = Math.floor(Math.random() * 7); //gives random number between 0-6
for (var i = 1; i <= 6; i++) {
if(i == correctAnswerIndex)
guess += '<option value="'+i+'">' + correctAns + '</option>';
else
guess += "<option value='" + i + "'>" + translate[RanNumbers[i]] + "</option>";
}
you will need just to adjust else statement, as RanNumbers may not have 6 items. So maybe to introduce additional counter that would be used insead of i. (something like translate[RanNumbers[counter++]])

Categories