【发布时间】:2021-12-09 16:27:43
【问题描述】:
我需要一个 3 维数组来计数 - 它需要动态增长。它由index、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[otr_entries_count][2] 替换otr_entries[0][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
}
}
【问题讨论】:
-
如果在循环中你试图添加到数组中,你需要 .push([count,"something","something2"])
-
如果要添加到数组中,则不应使用与循环控件相同的数组。
-
亲爱的彼得,非常感谢。这个答案解决了它。我不得不摆弄一下,但效果很好。我现在将尝试从内存中附加解决方案。你也可以提出一个答案,我会选择它。谢谢。
标签: javascript arrays greasemonkey