我开始研究用JavaScript读取本地json文件,并试图将其放入Google图表中,但是我的while循环遇到了问题,如下所示。 Var c调用一个函数来计算json文件中的数据行。

 function drawChart() {
    var soData = JSON.parse(staffOrders);
    var i = 0;
    var c = getRowCount(); //returns 5

    // Create the data table.
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Staff');
    data.addColumn('number', 'Orders Filled');
    //works
    //data.addRows([
      //['John', 3],
      //['Tommy', 1],
      //['Ken', 1],
      //['Sally', 1],
      //["Missy", 2]
    //]);

    //works
    data.addRows([
        [soData[0].staffName, Number(soData[0].orders)],
        [soData[1].staffName, Number(soData[1].orders)],
        [soData[2].staffName, Number(soData[2].orders)],
        [soData[3].staffName, Number(soData[3].orders)],
        [soData[4].staffName, Number(soData[4].orders)]
    ]);

    //***error - below doesn't render
    //also need to remove comma in last row as it isn't needed
    //data.addRows([
        //while (i <= c) {
            //[soData[i].staffName, Number(soData[i].orders)],
            //i++;
        //}
    //]);

最佳答案

您的代码正在尝试将while循环发送到data.addRows()。将函数调用移入while循环

while (i <= c) {
    data.addRows([[soData[i].staffName, Number(soData[i].orders)]]);
    i++;
}

09-30 22:23