I have several variables that I want to be able to use that are numbers for an equation. But in order to get to those variables, I am having to string together two variables to get this number. The problem I have is I don't understand the syntax to use that variable as a number instead of the concatenated name.
Here are the variables with their associated numbers:
var drygood = 0.9;
var dryaverage = 0.8;
var drybad = 0.7;
var wetgood = 0.7;
var wetaverage = 0.6;
var wetbad = 0.5;
var snowygood = 0.3;
var snowyaverage = 0.3;
var snowybad = 0.3;
var icygood = 0.1;
var icyaverage = 0.1;
var icybad = 0.1;
The words are made from climate (dry, wet, snowy, icy) and tire condition (good, average, bad).
I randomly pick a word from the first array and the second array and concatenate them.
So, I end up with one of the words in the above variables.
const tires = ["good", "average", "bad"];
const tireCondition = Math.floor(Math.random() * tires.length);
console.log(tireCondition, tires[tireCondition]);
const coldClimates = ["dry", "wet", "icy", "snowy"];
const randomTireCold = Math.floor(Math.random() * coldClimates.length);
console.log(randomTireCold, coldClimates[randomTireCold]);
The console logs confirm I am getting the concatenation and that the string returned is correct. But then I need to put that into an equation:
let stoppingDistMapOne = ((+velocitySquared / (2 * coldClimates[randomTireCold] + tires[tireCondition] * 9.81)) + +reactionTimeDistance);
coldClimates[randomTireCold] + tires[tireCondition] = the variable name already given, but it doesn't convert that to the number. So, I am guessing I am missing some syntax. I get the correct variable name, but not the number associated with that variable.
Any help greatly appreciated.
Use an object to use the key you generate.
var conditions = {
drygood: 0.9,
dryaverage: 0.8,
drybad: 0.7,
wetgood: 0.7,
wetaverage: 0.6,
wetbad: 0.5,
snowygood: 0.3,
snowyaverage: 0.3,
snowybad: 0.3,
icygood: 0.1,
icyaverage: 0.1,
icybad: 0.1
};
const tires = ["good", "average", "bad"];
const tireCondition = Math.floor(Math.random() * tires.length);
const keyCond = tires[tireCondition];
const coldClimates = ["dry", "wet", "icy", "snowy"];
const randomTireCold = Math.floor(Math.random() * coldClimates.length);
const keyClim = coldClimates[randomTireCold];
console.log(conditions[keyClim + keyCond]);
Or make it more readable with a better object structure.
var conditions = {
dry: {
good: 0.9,
average: 0.8,
bad: 0.7
},
wet: {
good: 0.7,
average: 0.6,
bad: 0.5
},
snowy: {
good: 0.3,
average: 0.3,
bad: 0.3
},
icy: {
good: 0.1,
average: 0.1,
bad: 0.1
}
};
const tires = ["good", "average", "bad"];
const tireCondition = Math.floor(Math.random() * tires.length);
const keyCond = tires[tireCondition];
const coldClimates = ["dry", "wet", "icy", "snowy"];
const randomTireCold = Math.floor(Math.random() * coldClimates.length);
const keyClim = coldClimates[randomTireCold];
console.log(conditions[keyClim][keyCond]);