Dylan Rolfe - 1 year ago 59
Javascript Question

# Calling an object that's in an object

I am working on a game that requires a random direction; either left, right, up, or down. Depending on certain variables, the chance of any specific direction being chosen changes. My first thought was to make an object with the different types of direction chances:

• Type L : 70% left, 10% right, 10% up, 10% down

• Type R : 10% left, 70% right, 10% up, 10% down

• Type U : 10% left, 10% right, 70% up, 10% down

• Type D : 10% left, 10% right, 10% up, 70% down

My first thought to go about doing this was to make an object with all the direction types and each type being an object.

``````var directions = {
L: {Left: 70, Right: 10, Up: 10, Down: 10},
R: {Left: 10, Right: 70, Up: 10, Down: 10},
U: {Left: 10, Right: 10, Up: 70, Down: 10},
D: {Left: 10, Right: 10, Up: 10, Down: 70}};
``````

where each number is the chance of that direction being called. I tried to call the chance of type L, left by using:

``````console.log(directions.L.Left);
``````

But it didn't work. If there is a better way to go about doing this or can help in any way, please tell me. Thanks.

Answer Source

Javascript is case-sensitive. Your code would have worked with the right casing

``````console.log(directions.L.Left); // note L in Left
``````

Example below

``````var directions = {
L: {Left: 70, Right: 10, Up: 10, Down: 10},
R: {Left: 10, Right: 70, Up: 10, Down: 10},
U: {Left: 10, Right: 10, Up: 70, Down: 10},
D: {Left: 10, Right: 10, Up: 10, Down: 70}};

console.log(directions.L.Left);``````

A word of advice - use decimals for percentage (ie, 0.7 for 70%) - it will make your code much simpler later on when you don't need to continually remember whether you've divided a variable by 100.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download