【问题标题】:Javascript nested for loop not returning array as expectedJavascript嵌套for循环未按预期返回数组
【发布时间】:2012-09-09 02:35:32
【问题描述】:

我无法理解这个家伙。我有一个通过 AJAX 读取的 CSV 文件,我正在根据返回的内容创建一个数组。我的 CSV 文件如下所示:

ID,name,address
0,john,123 fake st
1,bruce,123 fake st
2,john,124 fake st
3,fred,125 fake st
4,barry,126 fake st

我通过 ajax 函数调用它:

if (window.XMLHttpRequest) {
    var ajax = new XMLHttpRequest();
} else var ajax = new ActiveXObject("Microsoft.XMLHTTP");

function include(src) {
    ajax.open('GET', src, false);
    ajax.send(null);
    return ajax.responseText;
}

然后像这样循环遍历它:

var bsf = include('csv.csv');
// construct an array from the first line of the file
// and use that array to name the keys in all further arrays
var cols = bsf.split('\r\n');
var ln1 = cols[0].split(',');
// pull out each line from bsf and turn it into an array
var line = [];
var table = {};
var curRow = [];

for (i = 1; i < cols.length; i++) { // i = 1 so we can skip the 'title' csv line
    curRow = cols[i].split(',');

    for (j = 0; j < curRow.length; j++) {
        line[ln1[j]] = curRow[j];
    }

    table[curRow[0]] = line;
}
console.dir(table);

我有 4 个数组,它们都包含 csv 文件的最后一行,而不是每行一个数组的对象。嵌套的 for 循环正确完成,如果我在将它输入到 table 对象之前 alert(line) ,它会正确返回当前行数组,但仍然不会将该数组分配给对象行。

我想去哪里

 table{
     0: [id: 0, name: 'john', address: '123 fake st'],
     1: [id: 1, name: 'bruce', address: '124 fake st'],
     ...}

我明白了

 table{
     4: [id: 4, name: 'barry', address: '126 fake st'],
     4: [id: 4, name: 'barry', address: '126 fake st'],
     etc.}

有什么想法吗?我感觉我在整个循环中都正确地分配了它们,但是在最后一次运行时,我错误地分配了它们并覆盖了正确的。

【问题讨论】:

  • 这个 csv 是动态生成的吗?如果是这样,服务器应该将其作为 json 字符串发送,省去您必须对 csv 数据进行客户端解析的所有麻烦。
  • 运行console.log(JSON.stringify(table));(捂脸)。 @Black_Stormy 你不应该使用 Arrays 你真正想要的是 Objects(Hashes)。

标签: javascript loops for-loop nested


【解决方案1】:

您的问题是您只有一个 line 数组,您可以一遍又一遍地重新填充:

for (j = 0; j < curRow.length; j++) {
    line[ln1[j]] = curRow[j];
}

然后将 line 数组添加到不同位置的 table

table[curRow[0]] = line;

结果是table 中的每个条目都将是cols 中的最后一行。

您只需将不同的数组放入table,如下所示:

for (i = 1; i < cols.length; i++) {
    line   = [ ]; // <-------- This is the important part!
    curRow = cols[i].split(',');
    for (j = 0; j < curRow.length; j++) {
        line[ln1[j]] = curRow[j];
    }
    table[curRow[0]] = line;
}

【讨论】:

  • 啊我需要重新初始化数组才能覆盖它的内容。我不知道这个。谢谢!
  • @Black_Stormy:你不是在重新初始化数组,而是在创建一个全新的数组,否则你最终会得到a = [...]; table[0] = a; table[1] = a;...
猜你喜欢
  • 2020-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
相关资源
最近更新 更多