2013-02-26 71 views
0

我試圖編寫一段簡單的JavaScript讀取CSV(粘貼到網頁上的textarea)並生成SQL插入語句,但是當我引用2D數組時,我一直收到未定義的值。 。訪問2D JavaScript數組

請幫忙!

var ret = ""; 
//alert("called"); 
//split the textarea into rows of text 
var lines = text.split("\n");   
//the first line of text is the table name 
var table = lines[0];     

//the second line of text is an array of the attribute names 
var attrnames = lines[1].split(",");   
var values = new Array(); 

//create a new array for each attribute 
for (var i = 0; i < attrnames.length; i++) { 
    //the length of each array is the total number of rows 
    //of text - 2 (title row and attr row) 
    values.push(new Array(lines.length - 2));  
} 

//for each subsequent row, push the values to the appropriate arrays 
for (var i = 2; i < lines.length; i++) { 
    //get the current row (value, value, value, value) 
    var thisrow = lines[i].split(",");   
    for (var j = 0; j < attrnames.length; j++) { 
     //add the j-th attribute (thisrow[j]) to its array (values[j]) 
     values[j].push(thisrow[j]);    
    } 
} 

var insertIntoTable = ""; 
var tableName = ""; 
var attrList = ""; 
var valueList = ""; 
var lead = ""; 

//loop through each row 
for (var k = 2; k < lines.length; k++) { 

    // --- ONE STATEMENT --- 
    //create the statements 
    insertIntoTable = "insert into table `"; 
    tableName = table; 
    attrList = "` ("; 
    valueList = "("; 
    for (var i = 0; i < attrnames.length; i++){ 
     attrList += "`" + attrnames[i] + "`,"; 
    } 

    //trim the last comma, then add the closing parenthesis. 
    attrList = attrList.substring(0, attrList.length-1) + ") "; 
    lead = insertIntoTable + tableName + attrList;  

    for (var i = 0; i < attrnames.length; i++) { 
     //this always points to undefined 
     valueList += "'" + values[i][k-2] + "', "; 
    } 

    lead += (" values " + valueList); 
    lead = lead.substring(0, lead.length-2) + ");\n"; 

    ret += lead; 

} 

alert(ret); 
+0

請勿將csv粘貼到文本框中,讓它們通過文件附件將其上傳 – 2013-02-26 00:31:19

+3

這不是某人粘貼到小Bobby表的鏈接嗎? – YXD 2013-02-26 00:32:32

+3

http://xkcd.com/327/ – 2013-02-26 00:33:25

回答

0

在JavaScript中,您不需要設置數組的長度。它們更像ArrayLists或其他東西;閱讀更多在MDN's documentation

當你

var x = new Array(10); // array with "length" set to 10 
x.push("somevalue"); 

則該值將在x[10]插入 - 在列表的末尾。將其記錄在控制檯中以便自己查看。

因此,要麼刪除push()並改爲使用絕對指示符,要麼將該數組初始化爲空 - 最好使用array literal syntax[]。那麼你的代碼的相關區域應該是這樣的:

//create a new empty array for each attribute 
for(var i = 0; i<attrnames.length; i++){ 
    values.push([]); 
} 
+0

謝謝Bergi,你是個紳士和學者:) – connerc 2013-02-26 00:43:58

0

你正在長n,其中n是行數,並然後你在數據n更多元素推的數組。從0開始長數組,你將被罰款:

//create a new array for each attribute 
for(var i = 0; i<attrnames.length; i++){ 
    values.push(new Array(0)); // or '[]' -> the length of each array **will be** the total number of rows of text-2 (title row and attr row) 
} 

我想補充警告說,粘貼的數據會容易出現大量的錯誤和潛在的安全問題,如SQL注入攻擊。除此之外,如果數據末尾還有額外的\n秒,會發生什麼情況?你將會得到更多未定義的數據。