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";
Firstly, to create an array, it’s better to use the square bracket notation (
[]):This is the way you emulate a multi-demensional array in JavaScript. It’s one or more arrays inside an array.
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:
Here is the code you were probably looking for:
But since you’re giving all the names the same URL, then you can use a
forloop instead to do this faster: