2016-11-14 99 views
1

我想我在這裏誤解了一些東西 - 我通常在PHP中工作,並認爲我錯過了一些小東西。我的最後一個數組tmp是空的,並顯示爲「,,,,,,,,,,,,,,,,」。在我看來,我的tmp數組可能在某處被清空,或者由於某種原因,範圍被重置。我使用它作爲表格中的座標,您可以選擇表格行併發布到web服務,但我的數組似乎是錯誤的。Javascript多維數組爲空

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; 

任何幫助將不勝感激。 編輯: 控制檯輸出示例。 enter image description here

+0

你確定getSelectedColumn和getSelectedRow工作正常嗎? – GiuServ

+0

添加輸出示例。 – Muppet

+0

只是一個例子嗎?我的意思是。 index [14] ['G']是否存在? – GiuServ

回答

1

我的最後一個數組tmp目錄是空的,顯示爲「,,,,,,,,,,,,,,,,」

隨着您設置非數字索引對象的字段而不是索引的元素。

如果你將有數字索引的二維數字數組類似如下:

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 '.' 
+0

你先生,是上帝!謝謝,我不知道它試圖將對象轉換爲字符串(在控制檯中),因此是空數組。 – Muppet

+0

@木偶我已經更新了答案,因爲你的問題是關於保存字母的引號。我想這對你有用。 –

0

你也可以做到這一點(用逗號,不是加):

console.log('Final Array: ', tmp); //empty?? 
console.log('Final Array: ', tmp[14]['G']);