Jak mogę utworzyć tablicę dwuwymiarową w JavaScript?
Czytałem w Internecie i niektóre miejsca mówią, że nie jest to możliwe, niektóre mówią, że jest, a potem dają przykład, a inne obalają przykład, itp.
-
Jak zadeklarować dwuwymiarową tablicę w JavaScript? (zakładając, że jest to możliwe)
Jak uzyskać dostęp do jego członków? (
myArray[0][1]
CzymyArray[0,1]
?)
30 answers
var items = [
[1, 2],
[3, 4],
[5, 6]
];
console.log(items[0][0]); // 1
console.log(items);
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-10 15:20:13
Po prostu uczynisz każdy element w tablicy tablicą.
var x = new Array(10);
for (var i = 0; i < x.length; i++) {
x[i] = new Array(3);
}
console.log(x);
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-08-29 08:56:37
Podobne do odpowiedzi activa, oto funkcja do tworzenia tablicy n-wymiarowej:
function createArray(length) {
var arr = new Array(length || 0),
i = length;
if (arguments.length > 1) {
var args = Array.prototype.slice.call(arguments, 1);
while(i--) arr[length-1 - i] = createArray.apply(this, args);
}
return arr;
}
createArray(); // [] or new Array()
createArray(2); // new Array(2)
createArray(3, 2); // [new Array(2),
// new Array(2),
// new Array(2)]
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-03-31 08:46:28
Javascript ma tylko tablice 1-wymiarowe, ale można budować tablice tablic, jak wskazywali inni.
Do zbudowania tablicy 2-d o stałych wymiarach można użyć następującej funkcji:
function Create2DArray(rows) {
var arr = [];
for (var i=0;i<rows;i++) {
arr[i] = [];
}
return arr;
}
Liczba kolumn nie jest tak naprawdę ważna, ponieważ nie jest wymagane określanie rozmiaru tablicy przed jej użyciem.
Wtedy możesz po prostu zadzwonić:
var arr = Create2DArray(100);
arr[50][2] = 5;
arr[70][5] = 7454;
// ...
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
2009-06-08 18:32:00
Najprostszy sposób:
var myArray = [[]];
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-01-22 18:47:57
Powodem, dla którego niektórzy mówią, że nie jest to możliwe, jest fakt, że tablica dwuwymiarowa jest tak naprawdę tylko tablicą tablic. Pozostałe komentarze tutaj dostarczają doskonale poprawnych metod tworzenia dwuwymiarowych tablic w JavaScript, ale najczystszym punktem widzenia byłoby to, że masz jednowymiarową tablicę obiektów, każdy z tych obiektów byłby jednowymiarową tablicą składającą się z dwóch elementów.
Więc to jest przyczyna sprzecznych punktów widzenia.
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
2009-06-08 18:33:44
Niewiele osób pokazuje użycie push:
Aby przynieść coś nowego, pokażę Ci, jak zainicjalizować matrycę z jakąś wartością, przykład: 0 lub pusty łańcuch"".
Przypominamy, że jeśli masz tablicę 10 elementów, w javascript ostatnim indeksem będzie 9!
function matrix( rows, cols, defaultValue){
var arr = [];
// Creates all lines:
for(var i=0; i < rows; i++){
// Creates an empty line
arr.push([]);
// Adds cols to the empty line:
arr[i].push( new Array(cols));
for(var j=0; j < cols; j++){
// Initializes:
arr[i][j] = defaultValue;
}
}
return arr;
}
Przykłady użycia:
x = matrix( 2 , 3,''); // 2 lines, 3 cols filled with empty string
y = matrix( 10, 5, 0);// 10 lines, 5 cols filled with 0
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-08 02:22:30
Dwuliniowe:
var a = [];
while(a.push([]) < 10);
Wygeneruje tablicę a o długości 10, wypełnioną tablicami. (Push dodaje element do tablicy i zwraca nową długość)
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
2014-05-26 10:00:12
Najbardziej rozsądną odpowiedzią wydaje się być
var nrows = ~~(Math.random() * 10);
var ncols = ~~(Math.random() * 10);
console.log(`rows:${nrows}`);
console.log(`cols:${ncols}`);
var matrix = new Array(nrows).fill(0).map(row => new Array(ncols).fill(0));
console.log(matrix);
Uwaga nie możemy bezpośrednio wypełnić wierszami, ponieważ fill używa płytkiego konstruktora kopiującego, dlatego wszystkie wiersze będą miały tę samą pamięć ...oto przykład, który pokazuje, jak każdy wiersz będzie współdzielony (zaczerpnięty z innych odpowiedzi):
// DON'T do this: each row in arr, is shared
var arr = Array(2).fill(Array(4));
arr[0][0] = 'foo'; // also modifies arr[1][0]
console.info(arr);
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-07-28 11:00:39
Najprostszy sposób:
var arr = [];
var arr1 = ['00','01'];
var arr2 = ['10','11'];
var arr3 = ['20','21'];
arr.push(arr1);
arr.push(arr2);
arr.push(arr3);
alert(arr[0][1]); // '01'
alert(arr[1][1]); // '11'
alert(arr[2][0]); // '20'
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-12-27 13:32:45
Oto co osiągnąłem:
var appVar = [[]];
appVar[0][4] = "bineesh";
appVar[0][5] = "kumar";
console.log(appVar[0][4] + appVar[0][5]);
console.log(appVar);
To napisał mi bineeshkumar
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-10 06:35:46
Jak utworzyć pustą dwuwymiarową tablicę (jednowierszową)
Array.from(Array(2), () => new Array(4))
2 i 4 są odpowiednio pierwszym i drugim wymiarem.
Wykorzystujemy Array.from
, które mogą przyjmować param podobne do tablicy i opcjonalne mapowanie dla każdego z elementów.
Array.from (arrayLike [, mapFn [, thisArg]])
var arr = Array.from(Array(2), () => new Array(4));
arr[0][0] = 'foo';
console.info(arr);
ta sama sztuczka może być użyta do tworzenia tablicy JavaScript zawierającej 1...N
Alternatywnie (ale bardziej nieefektywne 12% z n = 10,000
)
Array(2).fill(null).map(() => Array(4))
Spadek wydajności wynika z faktu, że musimy mieć zainicjalizowane pierwsze wartości wymiarów, aby uruchomić .map
. Pamiętaj, że Array
nie przydzieli pozycji, dopóki nie zamówisz jej przez .fill
lub bezpośrednie przypisanie wartości.
var arr = Array(2).fill(null).map(() => Array(4));
arr[0][0] = 'foo';
console.info(arr);
Kontynuacja
Dlaczego to nie działa?
Array(2).fill(Array(4));
While it does return pozornie pożądana tablica dwuwymiarowa ([ [ <4 empty items> ], [ <4 empty items> ] ]
), istnieje haczyk: tablice pierwszego wymiaru zostały skopiowane przez odniesienie. Oznacza to, że arr[0][0] = 'foo'
zmieniłby dwa wiersze zamiast jednego.
var arr = Array(2).fill(Array(4));
arr[0][0] = 'foo';
console.info(arr);
console.info(arr[0][0], arr[1][0]);
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 22:38:54
Tablice dwuwymiarowe są tworzone tak samo jak tablice jednowymiarowe. I masz do nich dostęp jak array[0][1]
.
var arr = [1, 2, [3, 4], 5];
alert (arr[2][1]); //alerts "4"
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
2009-06-08 18:27:57
Nie jestem pewien, czy ktoś na to odpowiedział, ale okazało się, że to działa dla mnie całkiem dobrze.]}
var array = [[,],[,]]
Eg:
var a = [[1,2],[3,4]]
Dla dwuwymiarowej tablicy, na przykład.
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
2012-07-01 06:50:41
Aby utworzyć tablicę 2D w javaScript możemy najpierw utworzyć tablicę, a następnie dodać Tablice jako jej elementy. Metoda ta zwróci tablicę 2D z podaną liczbą wierszy i kolumn.
function Create2DArray(rows,columns) {
var x = new Array(rows);
for (var i = 0; i < rows; i++) {
x[i] = new Array(columns);
}
return x;
}
Aby utworzyć tablicę użyj tej metody jak poniżej.
var array = Create2DArray(10,20);
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
2014-06-26 06:56:28
Użyj Składni Tablic
W JavaScript 1.7 i nowszych można używać składanie tablic do tworzenia dwuwymiarowych tablic. Można również filtrować i/lub manipulować wpisami podczas wypełniania tablicy i nie trzeba używać pętli.
var rows = [1, 2, 3];
var cols = ["a", "b", "c", "d"];
var grid = [ for (r of rows) [ for (c of cols) r+c ] ];
/*
grid = [
["1a","1b","1c","1d"],
["2a","2b","2c","2d"],
["3a","3b","3c","3d"]
]
*/
Możesz utworzyć dowolną tablicę n x m
i wypełnić ją wartością domyślną wywołując
var default = 0; // your 2d array will be filled with this value
var n_dim = 2;
var m_dim = 7;
var arr = [ for (n of Array(n_dim)) [ for (m of Array(m_dim) default ]]
/*
arr = [
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
]
*/
Więcej przykładów i dokumentacji można znaleźć tutaj .
Należy pamiętać, że nie jest to standard feature yet .
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-08-11 17:33:39
Dla miłośników jednej linii Array.od()
// creates 8x8 array filed with "0"
const arr2d = Array.from({ length: 8 }, () => Array.from({ length: 8 }, () => "0"));
Kolejny (z komentarza dymitra_romanowa) używa Array ().wypełnij()
// creates 8x8 array filed with "0"
const arr2d = Array(8).fill(0).map(() => Array(8).fill("0"));
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-07-01 20:00:35
Moje podejście jest bardzo podobne do @Bineesh answer, ale z bardziej ogólnym podejściem.
Możesz zadeklarować tablicę podwójną w następujący sposób:
var myDoubleArray = [[]];
Oraz przechowywanie i dostęp do zawartości w następujący sposób:
var testArray1 = [9,8]
var testArray2 = [3,5,7,9,10]
var testArray3 = {"test":123}
var index = 0;
myDoubleArray[index++] = testArray1;
myDoubleArray[index++] = testArray2;
myDoubleArray[index++] = testArray3;
console.log(myDoubleArray[0],myDoubleArray[1][3], myDoubleArray[2]['test'],)
To wyświetli oczekiwane wyjście
[ 9, 8 ] 9 123
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-01-14 00:25:07
Znalazłem poniżej najprostszy sposób:
var array1 = [[]];
array1[0][100] = 5;
alert(array1[0][100]);
alert(array1.length);
alert(array1[0].length);
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
2014-04-15 09:14:47
Musiałem zrobić elastyczną funkcję tablicy, aby dodać "rekordy" do niego, jak potrzebowałem i być w stanie je zaktualizować i wykonać wszelkie obliczenia e potrzebne, zanim wysłałem go do bazy danych do dalszego przetwarzania. Oto kod, mam nadzieję, że pomoże :).
function Add2List(clmn1, clmn2, clmn3) {
aColumns.push(clmn1,clmn2,clmn3); // Creates array with "record"
aLine.splice(aPos, 0,aColumns); // Inserts new "record" at position aPos in main array
aColumns = []; // Resets temporary array
aPos++ // Increments position not to overlap previous "records"
}
Zapraszam do optymalizacji i / lub wskazywania błędów:)
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
2012-10-12 10:59:19
Javascript nie obsługuje tablic dwuwymiarowych, zamiast tego przechowujemy tablicę wewnątrz innej tablicy i pobieramy dane z tej tablicy w zależności od pozycji tablicy, do której chcesz uzyskać dostęp. Zapamiętaj numerację tablicy rozpoczynającą się od zera .
Przykład Kodu:
/* Two dimensional array that's 5 x 5
C0 C1 C2 C3 C4
R0[1][1][1][1][1]
R1[1][1][1][1][1]
R2[1][1][1][1][1]
R3[1][1][1][1][1]
R4[1][1][1][1][1]
*/
var row0 = [1,1,1,1,1],
row1 = [1,1,1,1,1],
row2 = [1,1,1,1,1],
row3 = [1,1,1,1,1],
row4 = [1,1,1,1,1];
var table = [row0,row1,row2,row3,row4];
console.log(table[0][0]); // Get the first item in the array
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-07-30 23:53:01
Poniżej tworzy macierz 5x5 i wypełnia ją null
var md = [];
for(var i=0; i<5; i++) {
md.push(new Array(5).fill(null));
}
console.log(md);
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-08-29 06:53:00
Oto szybki sposób na stworzenie dwuwymiarowej tablicy.
function createArray(x, y) {
return Array.apply(null, Array(x)).map(e => Array(y));
}
Możesz łatwo przekształcić tę funkcję w funkcję ES5.
function createArray(x, y) {
return Array.apply(null, Array(x)).map(function(e) {
return Array(y);
});
}
Dlaczego to działa: konstruktor new Array(n)
tworzy obiekt z prototypem Array.prototype
, a następnie przypisuje obiektowi length
, w wyniku czego powstaje niepopularna tablica. Z powodu braku rzeczywistych członków nie możemy uruchomić na nim funkcji Array.prototype.map
.
Jednakże, gdy podasz konstruktorowi więcej niż jeden argument, np. gdy jeśli wykonasz Array(1, 2, 3, 4)
, konstruktor użyje obiektu arguments
do poprawnego tworzenia instancji i wypełniania obiektu Array
.
Z tego powodu możemy użyć Array.apply(null, Array(x))
, Ponieważ funkcja apply
rozdzieli argumenty do konstruktora. Dla wyjaśnienia, Robienie Array.apply(null, Array(3))
jest równoznaczne z robieniem Array(null, null, null)
.
Teraz, gdy stworzyliśmy rzeczywistą wypełnioną tablicę, wystarczy wywołać map
i utworzyć drugą warstwę (y
).
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-03-25 05:56:18
Można przydzielić tablicę wierszy, gdzie każdy wiersz jest tablicą o tej samej długości. Można też przydzielić jednowymiarową tablicę z elementami rows * columns i zdefiniować metody mapowania współrzędnych wierszy/kolumn do indeksów elementów.
Bez względu na to, którą implementację wybierzesz, jeśli zawiniesz ją w obiekt, możesz zdefiniować metody accessora w prototypie, aby API było łatwe w użyciu.
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
2009-06-08 18:32:38
Znalazłem, że ten kod działa dla mnie:
var map = [
[]
];
mapWidth = 50;
mapHeight = 50;
fillEmptyMap(map, mapWidth, mapHeight);
...
function fillEmptyMap(array, width, height) {
for (var x = 0; x < width; x++) {
array[x] = [];
for (var y = 0; y < height; y++) {
array[x][y] = [0];
}
}
}
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
2014-06-14 15:46:56
Uproszczony przykład:
var blocks = [];
blocks[0] = [];
blocks[0][0] = 7;
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-09-21 07:05:23
Jedna Liniatura do tworzenia macierzy m * n 2 wymiarowej wypełnionej 0.
new Array(m).fill(new Array(n).fill(0));
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-01-03 01:07:45
var playList = [
['I Did It My Way', 'Frank Sinatra'],
['Respect', 'Aretha Franklin'],
['Imagine', 'John Lennon'],
['Born to Run', 'Bruce Springsteen'],
['Louie Louie', 'The Kingsmen'],
['Maybellene', 'Chuck Berry']
];
function print(message) {
document.write(message);
}
function printSongs( songs ) {
var listHTML = '<ol>';
for ( var i = 0; i < songs.length; i += 1) {
listHTML += '<li>' + songs[i][0] + ' by ' + songs[i][1] + '</li>';
}
listHTML += '</ol>';
print(listHTML);
}
printSongs(playList);
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-10-03 15:22:59
Dokonałem modyfikacji odpowiedzi Matthew Crumley na stworzenie wielowymiarowej funkcji tablicy. Dodałem wymiary tablicy, która ma być przekazana jako zmienna array i pojawi się kolejna zmienna - value
, która będzie używana do ustawiania wartości elementów ostatnich tablic w tablicy wielowymiarowej.
/*
* Function to create an n-dimensional array
*
* @param array dimensions
* @param any type value
*
* @return array array
*/
function createArray(dimensions, value) {
// Create new array
var array = new Array(dimensions[0] || 0);
var i = dimensions[0];
// If dimensions array's length is bigger than 1
// we start creating arrays in the array elements with recursions
// to achieve multidimensional array
if (dimensions.length > 1) {
// Remove the first value from the array
var args = Array.prototype.slice.call(dimensions, 1);
// For each index in the created array create a new array with recursion
while(i--) {
array[dimensions[0]-1 - i] = createArray(args, value);
}
// If there is only one element left in the dimensions array
// assign value to each of the new array's elements if value is set as param
} else {
if (typeof value !== 'undefined') {
while(i--) {
array[dimensions[0]-1 - i] = value;
}
}
}
return array;
}
createArray([]); // [] or new Array()
createArray([2], 'empty'); // ['empty', 'empty']
createArray([3, 2], 0); // [[0, 0],
// [0, 0],
// [0, 0]]
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-05-23 12:03:09
Funkcja rekurencyjna do tworzenia wielowymiarowej tablicy:
var makeArray = function (dims, arr) {
if (dims[1] === undefined) {
return new Array(dims[0]);
}
arr = new Array(dims[0]);
for (var i=0; i<dims[0]; i++) {
arr[i] = new Array(dims[1]);
arr[i] = makeArray(dims.slice(1), arr[i]);
}
return arr;
}
Zbuduj tablicę 2X3X4X2 4D:
var array = makeArray([2, 3, 4, 2]);
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-05-05 19:55:06