簡體   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