简体   繁体   English

用Javascript将数据追加到多维数组

[英]Appending data into multidimensional array in Javascript

I am writing PHP code around into Node.js and I have come to halt on part where program is dealing with multidimensional arrays. 我正在将PHP代码编写到Node.js中,而我在程序处理多维数组的部分已经停下来了。

In PHP I got this (removed for loop to simplify it): 在PHP中,我得到了这个(为简化起见,删除了for循环):

$tables = [];
$left_over_array = [34, 35, 36, 37];
$round = 0;
$row = 0;
$tables['round_'.$round][$row][]=$left_over_array[0];
$tables['round_'.$round][$row][]=$left_over_array[1];
$tables['round_'.$round][$row+3][]=$left_over_array[0];
$tables['round_'.$round][$row+3][]=$left_over_array[1];

Edit: $row value is not in 0,1,2,3 but maybe in 0, 1, 10, 3, 12 order. 编辑: $row值不在0,1,2,3但也许在0, 1, 10, 3, 12秩序。

Outcome of PHP code would look something like this: PHP代码的结果如下所示:

$tables = [
              'round_0'=>[
                  '0'=>[
                      0=>34,
                      1=>35
                  ],
                  '3'=>[
                      0=>36,
                      1=>37
                  ],
               ]
          ]

Later I need to access this data. 稍后我需要访问此数据。 When I have it in this structure I can simply do $tables['round_0'][3][1] to get value 36 当我在这种结构中拥有它时,我可以简单地执行$tables['round_0'][3][1]以获取值36

My question is, how to achieve same thing with Javascript? 我的问题是,如何用Javascript实现同一目标? or should I instead use objects? 还是应该使用对象? and then how do I do same thing with object 然后我该如何处理对象

Javascript associative arrays have to be declared as objects, and the key have to exist before you try to put anything inside of it. 必须将Javascript关联数组声明为对象,并且在尝试将任何内容放入其中之前,键必须存在。

So, following my code, I prepared a loop from 0 to 9, then check if the specific round_{number} is undefined. 因此,按照我的代码,我准备了一个从0到9的循环,然后检查特定的round_ {number}是否未定义。 If so, I set the key as an array, and just then I add the elements to it, similarly to the [] from php, but with the function push() from Javascript. 如果是这样,我将键设置为数组,然后将其添加到元素中,类似于php中的[] ,但使用Javascript中的push()函数。

 var tables = []; var left_over_array = [34, 35, 36, 37]; for (var round = 0; round < 10; round++) { if (tables['round_'+round] == undefined) { tables['round_'+round] = []; } tables['round_'+round].push([ left_over_array[0], left_over_array[1], ]); tables['round_'+round].push([ left_over_array[2], left_over_array[3], ]); } console.log(tables['round_0'][0][1]); 

SOLVED 解决了

 var tables = []; var left_over_array = [34, 35, 36, 37]; var round = 0; var row = 0; tables['round_'+round] = []; //In JS initialization before assignment is important tables['round_'+round][row+3] = [ left_over_array[0], left_over_array[1], ]; tables['round_'+round][row+10] = [ left_over_array[3], left_over_array[1], ]; console.log(tables['round_0'][3][1]); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM