Zadeklarować pustą dwuwymiarową tablicę w Javascript?

Chcę utworzyć dwuwymiarową tablicę w Javascript, w której będę przechowywać współrzędne (x,y). Nie wiem jeszcze ile par współrzędnych będę miał, ponieważ będą one dynamicznie generowane przez wejście użytkownika.

Przykład wstępnie zdefiniowanej tablicy 2d:

var Arr=[[1,2],[3,4],[5,6]];

Myślę, że mogę użyć metody PUSH, aby dodać nowy rekord na końcu tablicy.

Jak zadeklarować pustą dwuwymiarową tablicę tak, że gdy użyję mojego pierwszego Arr.push() zostanie dodana do indeksu 0, i każdy kolejny rekord napisany przez Pusha będzie miał następny indeks?

Jest to prawdopodobnie bardzo łatwe do zrobienia, jestem tylko nowicjuszem z JS, i byłbym wdzięczny, gdyby ktoś mógł napisać krótki działający fragment kodu, który mógłbym zbadać. Dzięki

Author: Zannix, 2013-08-10

9 answers

Możesz po prostu zadeklarować regularną tablicę w ten sposób:

var arry = [];

Wtedy, gdy masz parę wartości do dodania do tablicy, wszystko, co musisz zrobić, to:

arry.push([value_1, value2]);

I tak, przy pierwszym wywołaniu arry.push, para wartości zostanie umieszczona w indeksie 0.

Z NodeJS repl:

> var arry = [];
undefined
> arry.push([1,2]);
1
> arry
[ [ 1, 2 ] ]
> arry.push([2,3]);
2
> arry
[ [ 1, 2 ], [ 2, 3 ] ]

Oczywiście, ponieważ javascript jest typowany dynamicznie, nie będzie żadnego kontrolera typu wymuszającego, aby tablica pozostała dwuwymiarowa. Musisz się upewnić, że dodajesz tylko pary współrzędnych i nie wykonuj następujących czynności:

> arry.push(100);
3
> arry
[ [ 1, 2 ],
  [ 2, 3 ],
  100 ]
 57
Author: DJG,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-10 15:33:27

Jeśli chcesz mieć dostęp do matrycy w ten sposób macierz [i] [j]

Uważam, że najbardziej wygodne jest inicjowanie go w pętli.

var matrix = [],
    cols = 3;

//init the grid matrix
for ( var i = 0; i < cols; i++ ) {
    matrix[i] = []; 
}

To da ci [ [], [], [] ]

Więc matryca[0] [0] matryca [1] [0] zwraca undefined i nie błąd "Uncaught TypeError: Cannot set property' 0 'of undefined"

 18
Author: Lorenzo Gangi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-26 18:46:08

Pusta tablica jest definiowana przez pominięcie wartości, tak jak:

v=[[],[]]
a=[]
b=[1,2]
a.push(b)
b==a[0]
 4
Author: UIlrvnd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-10 15:17:59

Można zagnieżdżać jedną tablicę w innej używając skróconej składni:

   var twoDee = [[]];
 4
Author: Kevin Bowersox,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-10 15:18:23

Możesz spróbować czegoś takiego: -

var arr = new Array([]);

Push data:

arr[0][0] = 'abc xyz';
 1
Author: Rahul Tripathi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-10 15:16:01

What ' s wrong with

var arr2 = new Array(10,20);
    arr2[0,0] = 5;
    arr2[0,1] = 2
    console.log("sum is   " + (arr2[0,0] +  arr2[0,1]))

Powinno odczytać "suma jest 7"

 1
Author: MadHaka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-20 06:24:05

Możesz wypełnić tablicę tablicami za pomocą funkcji:



var arr = [];
var rows = 11;
var columns = 12;

fill2DimensionsArray(arr, rows, columns);

function fill2DimensionsArray(arr, rows, columns){
    for (var i = 0; i < rows; i++) {
        arr.push([0])
        for (var j = 0; j < columns; j++) {
            arr[i][j] = 0;
        }
    }
}

Wynik jest następujący:



Array(11)
0:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
1:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
2:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
3:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
4:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
5:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
6:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
7:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
8:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
9:(12) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
10:(12)[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

 1
Author: Toni Perez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-09 11:30:52

Jeśli chcesz zainicjować wraz z tworzeniem, możesz użyć fill i map .

const matrix = new Array(5).fill(0).map(() => new Array(4).fill(0));

5 to liczba wierszy, a 4 to liczba kolumn.

 1
Author: AbhinavD,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-11 04:07:25

Zazwyczaj znamy liczbę kolumn, ale może nie wierszy (rekordów). Oto przykład mojego rozwiązania wykorzystującego wiele z powyższych tutaj. (Dla tych tutaj bardziej doświadczonych w JS niż ja-prawie everone-wszelkie sugestie poprawy kodu mile widziane)

     var a_cols = [null,null,null,null,null,null,null,null,null];
     var a_rxc  = [[a_cols]];

     // just checking  var arr =  a_rxc.length ; //Array.isArray(a_rxc);
     // alert ("a_rxc length=" + arr) ; Returned 1 
     /* Quick test of array to check can assign new rows to a_rxc. 
        i can be treated as the rows dimension and  j the columns*/
       for (i=0; i<3; i++) {
          for (j=0; j<9; j++) {
            a_rxc[i][j] = i*j;
            alert ("i=" + i + "j=" + j + "  "  + a_rxc[i][j] );
           }
          if (i+1<3) { a_rxc[i+1] = [[a_cols]]; }
        }

I jeśli przekazujemy tę tablicę do sever ' a ajax który działa dla mnie to

 $.post("../ajax/myservercode.php",
       {
        jqArrArg1 : a_onedimarray,
        jqArrArg2 : a_rxc
       },
       function(){  },"text" )
        .done(function(srvresp,status) { $("#id_PageContainer").html(srvresp);} ) 
        .fail(function(jqXHR,status) { alert("jqXHR AJAX error " + jqXHR + ">>" + status );} );
 -2
Author: GMC,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-15 00:19:44