我需要一个三维数组来计数-它需要动态增长。它由索引、string1和string2组成。
这正是我想要的输出(对于单个循环,因为数组只是硬编码到索引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
}
}但是,当我用otr_entries[0][2]替换otr_entries[otr_entries_count][2]时,如果计数不是0,脚本就会突然失败。这意味着,数组不仅仅是在增长。那么,如何将其存档呢?
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
}
}编辑:
这是我的解决方案,多亏了彼得斯的帮助。效果很好。
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
}
}发布于 2021-12-09 21:18:07
如果在循环中试图添加到数组中,则需要执行otr_entries.push(计数、“某事”、"something2")。
另外,如果要添加到数组中,则不应该使用与循环控件相同的数组。
发布于 2021-12-09 16:40:09
在数组中添加新项之前,您只是在递增计数器。解决方案是在最后移动计数器增量行:
这对我来说很管用
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;
}
}https://stackoverflow.com/questions/70293351
复制相似问题