繁体   English   中英

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

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

我不断收到此错误,这使我感到困惑。

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];
    }
}

基本上,您需要在使用它们之前声明和初始化数组。

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];
    }
}

var关键字用于声明新变量,并可选地对其进行初始化。 在普通作业中不使用它。 而且在要声明的变量中包含索引是没有意义的-索引用于访问数组的内容,而不声明任何内容。

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