访问2D JavaScript数组
问题描述:
我试图编写一段简单的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);
答
在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
答
你正在长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
秒,会发生什么情况?你将会得到更多未定义的数据。
请勿将csv粘贴到文本框中,让它们通过文件附件将其上传 – 2013-02-26 00:31:19
这不是某人粘贴到小Bobby表的链接吗? – YXD 2013-02-26 00:32:32
http://xkcd.com/327/ – 2013-02-26 00:33:25