[英]JavaScript: Creating mulitdimensional array
我制作了一個數組,該數組用於遍歷一個表(最初是隱藏的)並根據所請求的部分顯示某些行:
var rows_per_section = [ {min: 0, max: 7}, {min: 7, max: 17}, {min: 17, max: 21}, {min: 21, max: 35}, {min: 35, max: 41}, {min: 41, max: 46}, {min: 46, max: 52},{min: 52, max: 56} ];
var rows_min = rows_per_section[section_no].min;
var rows_max = rows_per_section[section_no].max;
我現在嘗試使用一個額外的功能來更改腳本,該功能可以遍歷表格並自行創建rows_per_section數組,因為表格的長度可以變化。 我可以通過查找類標記來檢測表中的中斷,但是我無法弄清楚每次中斷時如何創建數組並添加新值:
function create_section_array(profile_table, no_of_sections) {
var section_counter = 0;
var rows_per_section = new Array(); //this is where it starts to go wrong
//need to create the array and stick in the
//MIN value for the first section as 0
for (i=0;i<profile_table.length-1;i++) {
var table_row = profile_table.item(i);
var row_content = table_row.getElementsByTagName("td");
if(row_content[0].className == "ProfileFormTitle") {
if(section_counter != 0) {
//if not the first section add a MAX value to
//rows_per_section[section_counter + 1]
}
if(section_counter != no_of_sections) {
//if not the last section add a MIN value to
//rows_per_section[section_counter]
}
section_counter++;
}
}
return rows_per_section;
}
我將修改您的函數,使其看起來像這樣:
function create_section_array (profile_table, no_of_sections) {
var section_counter = 0,
rows_per_section = [ { min: 0 } ],
precedingLength = 0,
i, row_content;
for (i = 0; i < profile_table.length; i += 1) {
row_content = profile_table[i].getElementsByTagName('td');
if (row_content[0].className === 'ProfileFormTitle') {
if (section_counter !== 0) {
rows_per_section[section_counter] = {
max: row_content.length - 1
};
}
if (section_counter !== no_of_sections) {
rows_per_section[section_counter].min = precedingLength;
}
section_counter += 1;
precedingLength += row_content.length;
}
}
return rows_per_section;
}
關於上述幾點注意事項:
i
最初沒有明確聲明,這意味着它存在於全球。 我已經添加了聲明。
JavaScript中沒有塊作用域,只有函數作用域( 提升了vars )。 我已將row_content
的聲明移至函數頂部,因為這是普遍的慣用風格。
運算符==
和!=
執行類型強制 。 堅持===
和!==
通常更安全。
您可以使用文字語法聲明數組,不需要new Array()
。 在您的情況下,我們使用[ { min: 0 } ]
進行初始化以設置基本的必需結構,但是更常見的是,您看到人們使用空數組[]
初始化。
同樣,在數組中設置新索引的值時,我們可以將文字對象語法用於所需的基本結構。 您的情況是{ max: row_content.length - 1 }
。
從技術上講,這不是多維數組,而是對象(或字典,地圖,鍵/值存儲,無論您想稱呼它們的什么)的數組。
我實際上並沒有執行以上操作,只是對您的問題的上下文有模糊的了解。 此代碼可能存在(可能是?)問題! :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.