我可以减少此方法来实例化对象并推入数组吗?

时间:2015-04-16 13:53:31

标签: javascript jquery

我正在将.csv文件读入数组。该文件只包含员工信息(姓氏,名字,工作等)。我最终想要创建一个矩阵,其中用每个人对象填充一维数组。这是我的代码:

function setStaffData() {
    /** @type {Array.<string>} */
    var lines = [],
        person = [];
    $.ajax({
        url: 'data/staff2.csv',
        contentType: "text/csv",
        async: false,
        success: function(text) {
            lines = text.split(/\n/);
        }
    });
    for (var i = 0; i < lines.length; i++) {
        lines[i] = lines[i].replace(/(\r\n|\n|\r)/gm,"");
        person[i] = lines[i].split(",");
        staff[i] = new PersonClass(person[i][0], person[i][1], person[i][2], person[i][3], person[i][4], person[i][5], person[i][6], person[i][7]);
    }
}

如何通过不使用person数组来缩短过程?

1 个答案:

答案 0 :(得分:1)

由于您似乎没有使用person中每个条目的内容超出其填充的循环迭代,您只需使用单个变量:

function setStaffData() {
    /** @type {Array.<string>} */
    var lines = [],
        person;
    $.ajax({
        url: 'data/staff2.csv',
        contentType: "text/csv",
        async: false,
        success: function(text) {
            lines = text.split(/\n/);
        }
    });
    for (var i = 0; i < lines.length; i++) {
        lines[i] = lines[i].replace(/(\r\n|\n|\r)/gm,"");
        person = lines[i].split(",");
        staff[i] = new PersonClass(person[0], person[1], person[2], person[3], person[4], person[5], person[6], person[7]);
    }
}

修改

可以进一步缩短这一点以消除lines数组:

function setStaffData() {
    /** @type {Array.<string>} */
    $.ajax({
        url: 'data/staff2.csv',
        contentType: "text/csv",
        // note: removed "async: false"
        success: function(text) {
            var lineRegex = new RegExp('.*\n', 'g');
            var match, line, person;
            while (match = lineRegex.exec(text)) {
                line = match[0].replace(/(\r\n|\n|\r)/gm,"");
                person = line.split(",");
                staff.push(new PersonClass(person[0], person[1], person[2], person[3], person[4], person[5], person[6], person[7]));
            }
        }
    });
}