2012-09-09 57 views
0

我無法讓我的頭圍繞這一個傢伙。我有一個通過AJAX讀取的CSV文件,我從返回的內容創建一個數組。我的CSV文件看起來像這樣:Javascript嵌套for循環不按預期返回陣列

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功能調用它:用一個陣列

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); 

取而代之的對象:

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; 
} 

,並遍歷它像這樣對於每一行,我有4個數組,都包含csv文件的最後一行。嵌套for循環正確完成,並且如果在將它輸入到表對象之前提醒(行),它將正確返回當前行數組,但仍不會將該數組分配給對象行。

,我想

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.} 

任何想法?我感覺到我在整個循環中都將它們全部正確地分配,但是在最後一次通過時,我將它們全部錯誤地分配並覆蓋了正確的。

+0

是否正在dymically生成此CSV?如果是這樣,服務器應該將它作爲json字符串發送出去,從而節省了必須對csv數據進行客戶端解析的麻煩。 –

+0

運行'console.log(JSON.stringify(table));'(facepalm)。 @Black_Stormy你不應該使用'Arrays',你真正想要的是'Objects'(哈希)。 – c69

回答

0

你的問題是,你只需要你補充一遍又一遍一個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; 
} 
+0

啊我需要重新初始化數組以覆蓋它的內容。我不知道這個。謝謝! –

+0

@Black_Stormy:你不需要重新初始化數組,因爲你正在創建一個全新的數組,否則最終會出現'a = [...];表[0] = a;表[1] = a; ...' –