简体   繁体   English

Javascript SyntaxError:缺少; before语句(for循环之后)

[英]Javascript SyntaxError: missing ; before statement (after for loop)

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. var关键字用于声明新变量,并可选地对其进行初始化。 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];
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM