I have made an array that is used to loop through a table (initially hidden) and display certain rows depending on which section is requested:
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;
I am now trying to alter the script with an extra function that cycles through the table and creates the rows_per_section array on its own as the length of the table can be varied. I can detect the breaks in the table by looking for a class tag but I cannot figure out how to create the array and add new values every time it hits a break:
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;
}
I would modify your function to look something like this:
A few notes on the above:
iwas not explicitly declared originally, meaning it existed globally. I’ve added the declaration.There is no block scope in JavaScript, only function scope (vars are hoisted). I’ve moved the declaration of
row_contentto the top of the function as that is the prevalent idiomatic style.The operators
==and!=perform type coercion. It is generally safer to stick to===and!==instead.You can declare arrays with literal syntax, there’s no need for
new Array(). In your case, we initialise using[ { min: 0 } ]to set up the basic required structure, but more commonly you see people initialise with the empty array,[].Likewise, when setting the value of new indices in the array, we can use literal object syntax for the basic required structure. In your case, this is
{ max: row_content.length - 1 }.Technically, this isn’t a multi-dimensional array, it is an array of objects (or dictionaries, maps, key/value stores, whatever you want to call them).
I haven’t actually run the above and only have a vague sense of the context to your problem. There may be (are probably?) issues with this code! 🙂