我觉得我在这里误解了一些东西 - 我通常在PHP工作,并认为我错过了一些小事。我的最终数组tmp为空,显示为“,,,,,,,,,,,,,,,,”。在我看来,我的tmp数组可能在某处被清空,或者由于某种原因范围被重置。我正在使用它作为表格中的坐标,您可以在其中选择表格行并发布到Web服务,但我的数组似乎是错误的。
var length = $("#arrayCount").html();
var letters = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var col = getSelectedColumn(); //for example sake lets say "B" is the selected column
var row = getSelectedRow(); //selected rows will be from "11" - "16"
var columnIndexStart = letters.indexOf(col[0]);
var tmp = [];
for(var i = row[0]; i <= row[1]; i++) //rows[0] = 11 and rows[1] = 16
{
tmp[i] = [];
for(var j = columnIndexStart; j < letters.length; j++) //columns and starts at index 1 if we work with "B"
{
var val = $("#" + i + "_" + letters[j]).html(); //using the row and letters as the associated DOM elements ID. Easier to retrieve it's HTML then.
if(val != undefined)
{
console.log("Index [" + i + "]['" + letters[j] + "'] = " + val); //works perfectly and prints as it should.
tmp[i]['"'+letters[j]+'"'] = val; //using quotes to save letters? Is this preferred?
}
}
}
console.log('Final Array: ' + tmp); //empty??
console.log('Final Array: ' + tmp[14]['G']); //testing HTML output. But is undefined.
return tmp;
答案 0 :(得分:1)
我的最终数组tmp为空,显示为&#34; ,,,,,,,,,,,,,,,,&#34;
使用非数字索引设置对象字段而不是索引元素。
如果您将使用具有如下数字索引的二维数字数组:
var tmp = [[1,2,3], [1,2,3]];
在console.log('tmp = ' + tmp);
后,您显然会得到输出字符串,如:
tmp = 1,2,3,1,2,3
因为当您尝试将数组转换为字符串时,它会将元素转换为字符串并用逗号表示它们。
但是,当您尝试使用非数字索引设置元素时,您将设置此对象的字段。
var tmp = [];
tmp['A'] = 123;
console.log("tmp = " + tmp); // tmp =
console.log(tmp.A); //123
所以,你的案例中的console.log
效果很好 - 它正在序列化二维数组的所有元素。但是没有第二级数组没有存储值,它只有字段,不包含在数组的字符串表示中。
您正在获取一组逗号,因为tmp
数组的每个子数组都不包含任何元素,因此它的字符串表示形式为空字符串。每个子数组都包含所需数据到其字段中。
当您执行字符串和对象的求和操作时,您强制对象转换为字符串表示形式。而不是这样,建议使用console.log(yourObj)
- 它将记录整个对象而不将其转换为字符串。
//使用引号保存字母?这是首选吗?
不,"A"
和A
是不同的标识符。
var s = new Object();
s['"A"'] = 123;
console.log(s['A']); //undefined
console.log(s['"A"']); //123
此外,如果您将字段设置为引号 - 您无法以正常样式获取字段:
console.log(s."A"); //syntax error : expected identifier after '.'
答案 1 :(得分:0)
您也可以这样做(使用逗号,而不是加号):
console.log('Final Array: ', tmp); //empty??
console.log('Final Array: ', tmp[14]['G']);