I need a 3 dimensional array to count up - it needs to grow dynamically. It consists of index, string1 and string2.
This outputs exactly, what I want (for a single loop, since the array is just hardcoded to index 0)
var otr_entries=[[0,"",""]];
var otr_entries_count=0;
some_working_for_loop()
{
if(is_important_value_to_save())
{
//otr_entries_count=otr_entries_count 1;
otr_entries[otr_entries_count][1]=xx[i].previousElementSibling.innerHTML;
otr_entries[otr_entries_count][2]=xx[i].innerHTML;
window.alert(otr_entries[otr_entries_count][1]); // Expected output
window.alert(otr_entries[otr_entries_count][2]); // Expected output
}
}
but when I replace otr_entries[0][2]
with otr_entries[otr_entries_count][2]
the script suddenly fails, if the count is not 0. That means, that the array is not just growing. So how can this be archived?
var otr_entries=[[0,"",""]];
var otr_entries_count=0;
just_some_perfectly_working_for_loop(;;)
{
if(is_important_value_to_save())
{
otr_entries_count=otr_entries_count 1; // Counting up breaks the code
otr_entries[otr_entries_count][1]=xx[i].previousElementSibling.innerHTML;
otr_entries[otr_entries_count][2]=xx[i].innerHTML;
window.alert(otr_entries[otr_entries_count][1]); // No output, script totally stops
window.alert(otr_entries[otr_entries_count][2]); // No output, script totally stops
}
}
EDIT:
This is my solution, thanks to peters help. Works perfectly fine.
var otr_entries=[];
var otr_entries_count=-1;
some_working_for_loop()
{
if(is_important_value_to_save())
{
otr_entries_count=otr_entries_count 1;
otr_entries.push(otr_entries_count,xx[i].previousElementSibling.innerHTML,xx[i].innerHTML)
window.alert(otr_entries[otr_entries_count][1]); // Expected output
window.alert(otr_entries[otr_entries_count][2]); // Expected output
}
}
CodePudding user response:
If in the loop you’re trying to add to the array you need to do otr_entries.push([count,"something","something2"]).
Also, if you’re adding to the array you shouldn’t be using that same array as your loop control.
CodePudding user response:
You're just incrementing the counter before you add new item in the array. The solution is to move the counter incrementing line at the end:
This worked for me
const otr_entries=[[0,"",""]];
const otr_entries_count=0;
for(const entry of otr_entries) {
// condition
if(true) {
otr_entries[otr_entries_count][1]='something';
otr_entries[otr_entries_count][2]='something else'
window.alert(otr_entries[otr_entries_count][1]);
window.alert(otr_entries[otr_entries_count][2]);
otr_entries_count =1;
}
}