访问2D javascript数组

Accessing 2D javascript array

本文关键字:数组 javascript 2D 访问      更新时间:2023-09-26

我试图编写一个简单的javascript片段,读取CSV(粘贴到网页上的文本区)并生成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);

在JavaScript中你不需要设置数组的长度。它们更像是数组列表之类的;在MDN的文档中阅读更多内容。

当你这样做

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

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

因此,您可以放弃push()并使用绝对索引,或者将数组初始化为空-最好使用数组字面语法:[]。代码的相关区域应该是这样的:

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

您正在制作一个长度为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,会发生什么?您将得到更多未定义的数据。