Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Oliver Sewell
16,425 PointsHi i'm stuck with some javascript if anyone could help :)
var names = ["squirtle", "pikachu", "charmander", "bulbasaur"];
var levels = [5,7,3,12,15];
var healths = [100,50,200,150];
var rand1 = Math.floor(Math.random() * names.length);
var rand2 = Math.floor(Math.random() * levels.length);
var rand3 = Math.floor(Math.random() * healths.length);
var pokemon = {
name: names[rand1],
level: levels[rand2],
health: healths[rand3]
}
window.onload = init;
function init() {
var generate = document.getElementById("generate");
generate.onclick = showAnswer;
}
function showAnswer(){
alert(pokemon.name);
alert(pokemon.level);
}
I'm trying to get it so when the user hits the generate button it will display a random pokemon name an level at random. Thank you in advance :)
3 Answers
Joni Laukkonen
15,429 PointsHello Oliver,
I played around with that code a little and I got it running as you hoped for (I guess) I added some commenting in there hopefully this helps.
var names = ["squirtle", "pikachu", "charmander", "bulbasaur"];
var levels = [5, 7, 3, 12, 15];
var healths = [100, 50, 200, 150];
// Get the button, and when the user clicks on it, execute showAnswer
document.getElementById("generate").onclick = function() {
showAnswer()
};
/* showAnswer */
function showAnswer() {
/* Get rand numbers in function so they reset when function fires again */
var rand1 = Math.floor(Math.random() * names.length);
var rand2 = Math.floor(Math.random() * levels.length);
var rand3 = Math.floor(Math.random() * healths.length);
var pokemon = {
name: names[rand1],
level: levels[rand2],
health: healths[rand3]
}
alert(pokemon.name);
alert(pokemon.level);
}
//Run first once when window loaded
window.onload = showAnswer();
Oliver Sewell
16,425 Pointshi Sebastian Haviland , it isn't generating a random pokemon name or level the same ones appear when i click generate
Oliver Sewell
16,425 PointsOliver Sewell
16,425 PointsThank you :)