Monday, May 20, 2024
10
rated 0 times [  14] [ 4]  / answers: 1 / hits: 62823  / 12 Years ago, sat, september 29, 2012, 12:00:00

I'm confused about how to create and access 2-dimensional arrays in javascript. Below is an array declaration in which I'm storing names of people and then the src for their image. When I try to access myArray[0][0] element I get 'D' and when I try to access myArray[0,0], I get Donald Duck. How can I access the img src myArray[0][0] = assets/scrybe.jpg ?



JS code:



var myArray = new Array(1);

myArray[0] = Donald Duck;
myArray[1] = Winnie Pooh;
myArray[2] = Komal Waseem;
myArray[3] = Hockey;
myArray[4] = Basketball;
myArray[5] = Shooting;
myArray[6] = Mickey Mouse;

myArray[0][0] = assets/scrybe.jpg;
myArray[1][0] = assets/scrybe.jpg;
myArray[2][0] = assets/scrybe.jpg;
myArray[3][0] = assets/scrybe.jpg;
myArray[4][0] = assets/scrybe.jpg;
myArray[5][0] = assets/scrybe.jpg;
myArray[6][0] = assets/scrybe.jpg;

More From » multidimensional-array

 Answers
22

Firstly, to create an array, it's better to use the square bracket notation ( [] ):



var myArray = [];


This is the way you emulate a multi-demensional array in JavaScript. It's one or more arrays inside an array.



var myArray = [
[], [] // two arrays
];


If you're asking if there's a way to declare an array as multi-dimensional, then no, there isn't. You can access them like this:



myArray[0][0]; // the 1st element of the first array in myArray
myArray[1][1]; // the 2nd element of the second array in myArray


Here is the code you were probably looking for:



var myArray = [
[Donald Duck, assets/scrybe.jpg],
[Winnie Pooh, assets/scrybe.jpg],
[Komal Waseem, assets/scrybe.jpg]
[/* and so on...*/]
];


But since you're giving all the names the same URL, then you can use a for loop instead to do this faster:



for (var i = 0; i < myArray.length; i++) {
myArray[i][1] = assets/scrybe.jpg;
}

[#82845] Thursday, September 27, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jocelynkarsynr

Total Points: 472
Total Questions: 98
Total Answers: 96

Location: Macau
Member since Mon, Nov 16, 2020
4 Years ago
jocelynkarsynr questions
Tue, Feb 8, 22, 00:00, 2 Years ago
Sat, Jul 11, 20, 00:00, 4 Years ago
Sun, May 10, 20, 00:00, 4 Years ago
Sat, Jan 18, 20, 00:00, 4 Years ago
;