我创建了一个数组,用于循环遍历表(最初是隐藏的)并根据请求的部分显示某些行:
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 中没有 block 作用域,只有函数作用域 ( vars are hoisted )。我已将
row_content
声明移至函数顶部,因为这是流行的惯用风格。运算符
==
和!=
perform type coercion 。一般来说,坚持使用===
和!==
会更安全。您可以使用文字语法声明数组,无需
new Array()
。在您的情况下,我们使用[ { min: 0 } ]
进行初始化来设置所需的基本结构,但更常见的是,您会看到人们使用空数组[]
进行初始化.同样,当在数组中设置新索引的值时,我们可以使用文字对象语法来实现所需的基本结构。在您的情况下,这是
{ max: row_content.length - 1 }
。从技术上讲,这不是一个多维数组,而是一个对象数组(或字典、 map 、键/值存储,无论您如何调用它们)。
我实际上并没有运行上面的代码,只是对您的问题的上下文有一个模糊的了解。此代码可能(很可能?)有问题! :)
关于JavaScript:创建多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14499228/