I keep getting this error and it's confusing me..
function calculate(){
var n = document.getElementById("noOfCourses").value;
for(var i = 0 ; i < n ; i++) {
var course[i] = document.getElementById("GPA" + i+1).value;
var hours[i] = document.getElementById("hours" + i+1).value;
// Calculate the product of Course GPA and Credit Hours
var product[i] = course[i] * hours[i];
}
}
Basically you need to declare and initialise arrays before using them.
function calculate(){
var n = document.getElementById("noOfCourses").value,
course = [], // declare and init before
hours = [], // declare and init before
product = []; // declare and init before
for(var i = 0 ; i < n ; i++) {
course[i] = document.getElementById("GPA" + i+1).value;
hours[i] = document.getElementById("hours" + i+1).value;
// Calculate the product of Course GPA and Credit Hours
product[i] = course[i] * hours[i];
}
}
The var
keyword is used to declare new variables, and optionally initialize them. It's not used in ordinary assignments. And it makes no sense to include an index in the variable being declared -- indexes are used to access the contents of an array, not declare anything.
function calculate(){
var n = document.getElementById("noOfCourses").value;
for(var i = 0 ; i < n ; i++) {
course[i] = document.getElementById("GPA" + i+1).value;
hours[i] = document.getElementById("hours" + i+1).value;
// Calculate the product of Course GPA and Credit Hours
product[i] = course[i] * hours[i];
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.