0

CSVを読み込んで(Webページのテキストエリアに貼り付けて)SQL挿入ステートメントを生成する単純なJavaScriptをコーディングしようとしていますが、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()代わりに絶対インデックスを使用するか、配列を空として初期化します-配列リテラル構文を使用するのが最適です:[]。コードの関連領域は次のようになります。

//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ある長さの配列を作成してから、データのより多くの要素をプッシュしています。長さ0の配列から始めれば、問題はありません。nn

//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 に答える