0

我正在尝试编写一段简单的 javascript 代码,它读取 CSV(粘贴到网页上的 textarea 中)并生成 SQL 插入语句,但是当我引用 2D 数组时,我不断得到未定义的值。

请帮忙!

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

2 回答 2

0

在 JavaScript 中,您不需要设置数组的长度。它们更像是 ArrayLists 什么的;在MDN 的文档中阅读更多内容。

当你这样做

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

然后该值将插入x[10]到列表末尾的 - 处。将其登录到控制台以自己查看。

因此,要么放弃push()并使用绝对 indizes,要么将数组初始化为空 - 最好使用数组文字语法: []。您的代码的相关区域应如下所示:

//create a new empty array for each attribute
for(var i = 0; i<attrnames.length; i++){
    values.push([]);
} 
于 2013-02-26T00:40:47.370 回答
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数据末尾有多余的 s 会怎样?您最终会得到更多未定义的数据。

于 2013-02-26T00:41:36.967 回答