0

我正在解析一个 csv 文件。我的目标是查找以“A”、“B”开头的名称并计算出现次数。以下代码的问题是它永远不会完成while循环。

HTML:

<form>
  <input type="button" id="csv1ButtonRun" value="Run" style="background-color: lightgray"/>
</form>

脚本包括:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="app.js"></script>
<script src="jquery.csv-0.71.js"></script>

JavaScript:

var babyCsv = " Jacob, 1, boy, 2010, Isabella, 1, girl, 2010, Ethan, 2, boy, 2010, Sophia, 2, girl, 2010, Michael, 3, boy, 2010, Emma, 3, girl, 2010, Jayden, 4, boy, 2010, Olivia, 4, girl, 2010, William, 5, boy, 2010, Ava, 5, girl, 2010, Alexander, 6, boy, 2010, Emily, 6, girl, 2010, Noah, 7, boy, 2010, Abigail, 7, girl, 2010, Daniel, 8, boy, 2010, Madison, 8, girl, 2010, Aiden, 9, boy, 2010, Chloe, 9, girl, 2010, Anthony, 10, boy, 2010, Mia, 10, girl, 2010, Joshua, 11, boy, 2010, Addison, 11, girl, 2010, Mason, 12, boy, 2010, Elizabeth, 12, girl, 2010, Christopher, 13, boy, 2010, Ella, 13, girl, 2010, Andrew, 14, boy, 2010, Natalie, 14, girl, 2010, David, 15, boy, 2010, Samantha, 15, girl, 2010, Matthew, 16, boy, 2010";

var data = $.csv.toArray(babyCsv);

$("#csv1ButtonRun").click(function() {

    var arrayLength = data.length / 4;
    var count1 = 0;
    var count2 = 0;
    var i = 0;

    while (i <= arrayLength) {

        var name = data[i * 4];
        if (name.substring(0, 2) == " A") {
            count1 = count1 + 1;
        }
        else if (name.substring(0, 2) == " B") {
            count2 = count2 + 1;
        };
        i++;
    };

    document.write(count1 + count2);
});
4

1 回答 1

5

jsFiddle

您的 CSV 数据格式不正确,因此您的 JS 对象没有任何有意义的结构。您应该使用换行符分隔文件中的各个记录(行)。使用逗号分隔单行中的值。喜欢:

var babyCsv = " Bryan, 1, boy, 2010 \n Isabella, 1, girl, 2010 \n Bobby, 2, boy, 2010 \n Sophia, 2, girl, 2010 \n Nina, 5, girl, 2010 \n Alexander, 6, boy, 2010 \n Aiden, 9, boy, 2010 \n Anthony, 10, boy, 2010";

然后使用适当的$.csv.toArrays方法解析数据并返回一个二维记录数组。然后,您的数组中的每个条目都针对一个孩子,格式如下:

[
    [name1, age1, gender1, year1],
    [name2, age2, gender2, year2],
    ...
];

最后,在你的循环中,你必须在name每次迭代中更新变量的值,这样你才能真正检查每个孩子;目前你没有改变name迭代之间的值。这非常适合for循环。$.trim尽管 jquery-csv 可能已经这样做了,但也可以轻松摆脱字符串开头的任何额外空格。所以你的最终代码看起来像:

var babyCsv = "..."; // your data here

var data = $.csv.toArrays(babyCsv);

$(function () {
    $("#csv1ButtonRun").click(function () {

        var count1 = 0;
        var count2 = 0;

        console.log("Num kids: " + data.length);

        for (var i = 0; i < data.length; i++) {
            var name = $.trim(data[i][0]); //name is first column

            if (name[0] == "A") {
                count1++;
            } else if (name[0] == "B") {
                count2++;
            };
        };

        console.log("Kids with A or B names: " + (count1 + count2));
    });
});
于 2014-08-14T03:29:18.240 回答