I am building a simple maths based game using numbers and shapes. I am trying to create a javascript multidimensional array but I am stumped. The array keys are to be used to refer to CSS styles and the array values are numbers so that I can use them for mathematical calculations.
I am having trouble in accessing the elements in the array. This is what my multidimensional array looks like currently.
var sides = [{'1':1},{'3':3},{'3a':3}];
The above array would refer to the following shapes (where a denotes that the shape is upside down). They are displayed using the CSS below.
shape-1shape-3shape-3a
.sides-1 {
background: url(../img/shape_1.png);
}
.sides-3 {
background: url(../img/shape_3.png);
}
.sides-3a {
background: url(../img/shape_3a.png);
}
I also define what number is displayed inside the shape using the CSS below:
number-1number-2
.number-1 {
background: url(../img/number_1.png);
}
.number-2 {
background: url(../img/number_2.png);
}
Within a for loop I I work out which shape and number to display using the following code: (this is pseudocode, and just to give you an idea)
for(i = 0; i < 15; i++) {
<div class='col-xs-4 num'>
<div class='cont'>
<div class='sides-" + sides[0] + "'></div>
<div class='number-" + number + "'>" + (number*sides[1]) + "</div>
</div>
</div>
}
<div class='sides-" + sides[0] + "'></div>
This should display the appropriate shape, like the ones below:
1-23-13a-2
The issue that I am having at the moment is that I get NaN errors when I calculate the multiplication and also the shape is not displayed which suggests that I am not referencing the array correctly.
1 Answer 1
Problem
What you have there is actually an array of objects. [] is for arrays, {} is for objects.
When you try to access sides[1] you are getting the object {'3':3}, as that is the item at index 1.
There are numerous way you could approach this problem, here are a couple of them:
Multidimensional Array Approach
For an array of arrays (multi-dimensional) try this:
var sides = [['1', 1],['3', 3],['3a', 3]];
and use it like so:
<div class='sides-" + sides[i][0] + "'></div>
<div class='number-" + number + "'>" + (number * sides[i][1]) + "</div>
Array of Objects Approach
If you prefer a more readable approach (in my opinion) you could stick with an array of objects, but use proper properties for your values. The choice of course is yours (and you could take this much further by having reusable object definition), but hopefully this will give you an idea of the difference with using objects:
var sides = [
{ name: '1', number: 1 },
{ name: '3', number: 3 },
{ name: '3a', number: 3 }
];
which you can use like so:
<div class='sides-" + sides[i].name + "'></div>
<div class='number-" + number + "'>" + (number * sides[i].number) + "</div>
3 Comments
Explore related questions
See similar questions with these tags.
sides[1]and friends you are really just referring to something that looks like {'3':3}