首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >javascript中的动态多维数组-计数不起作用

javascript中的动态多维数组-计数不起作用
EN

Stack Overflow用户
提问于 2021-12-09 16:27:43
回答 2查看 50关注 0票数 0

我需要一个三维数组来计数-它需要动态增长。它由索引、string1和string2组成。

这正是我想要的输出(对于单个循环,因为数组只是硬编码到索引0)。

代码语言:javascript
复制
   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,脚本就会突然失败。这意味着,数组不仅仅是在增长。那么,如何将其存档呢?

代码语言:javascript
复制
   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
      }
   }

编辑:

这是我的解决方案,多亏了彼得斯的帮助。效果很好。

代码语言:javascript
复制
   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
      }
   }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-12-09 21:18:07

如果在循环中试图添加到数组中,则需要执行otr_entries.push(计数、“某事”、"something2")。

另外,如果要添加到数组中,则不应该使用与循环控件相同的数组。

票数 0
EN

Stack Overflow用户

发布于 2021-12-09 16:40:09

在数组中添加新项之前,您只是在递增计数器。解决方案是在最后移动计数器增量行:

这对我来说很管用

代码语言:javascript
复制
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;
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70293351

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档