1

In my program, I have the user fill in various fields and choose a pokemon, and it will calculate its stats. I have the arrays under the pokemon names, and a drop down to choose which pokemon's stats to calculate. I then use eval() to change the string in the dropdown into the array's name in order to do the calculations. The full program can be found with this link

https://studio.code.org/projects/applab/8N1yw5e0CcjTik0rsmp2mgW0TSoU7DSge8k8j5mlhw0

but a simplified version is

var venusaur = [20, 10, 5, 10, 20]
var blastoise = [50, 50, 50, 10, 5]
var charizard = [100, 10, 5, 10, 100]
var mon = getText("dropdown");
findStats(eval(mon));

before I added the eval, it was much clunkier code, and would only get worse as I added more pokemon, a simpler version of which is

var venusaur = [20, 10, 5, 10, 20];
var blastoise = [50, 50, 50, 10, 5];
var charizard = [100, 10, 5, 10, 100];
if (getText(dropdown)=="venusaur"){
    findStats(venusaur);
} else if (getText(dropdown)=="blastoise"){
    findStats(blastoise);
} else if getText(dropdown)=="charizard"){
    findStats(charizard);
}

I was just wondering if in this case, eval() was usable, as I've heard almost exclusively bad things about it, and I figured if there's a better way to accomplish this task, maybe I could learn it. Thanks in advance

3
  • eval is almost never the solution.... Nov 13, 2018 at 18:23
  • that's why i asked here, to find if this is an exception or if there's something i could do better
    – Ian Brown
    Nov 13, 2018 at 18:24
  • Use an object with pokemon names as the keys instead.
    – Andy
    Nov 13, 2018 at 18:25

2 Answers 2

3

Use an object and reference the object instead of using a bunch of global variables.

var pokes = {
 venusaur: [20, 10, 5, 10, 20],
 blastoise: [50, 50, 50, 10, 5],
 charizard: [100, 10, 5, 10, 100]
}
var mon = getText("dropdown");
console.log(pokes[mon])
1
  • thanks, that helped a ton, for some reason my programming class never mentioned objects, so thanks for adding another tool to my repertoire
    – Ian Brown
    Nov 13, 2018 at 18:37
0

I think you're trying to do something like that...

const stats = {
  venusaur: [20, 10, 5, 10, 20],
  blastoise: [50, 50, 50, 10, 5],
  charizard: [100, 10, 5, 10, 100],
};

const sel = document.querySelector('select');

const getStats = (e) => {
  const res = document.getElementById("result");
  res.innerHTML = stats[e.target.value] || 'not found';
}

sel.addEventListener('change', getStats);
<select>
  <option value="null">Select...</option>
  <option value="venusaur">Venusaur</option>
  <option value="blastoise">Blastoise</option>
  <option value="charizard">Charizard</option>
</select>

<div id="result"></div>

Not the answer you're looking for? Browse other questions tagged or ask your own question.