dimanche 13 décembre 2020

How come I can't get a random variable out of my array? The console.log() function always outputs same variable

//variable holding my monsters
var monsters = ["slug", "zombie", "wasp"];

//variable that gets a random monster out of my array
var randomMonster = Math.floor(Math.random() * monsters.length);
console.log(randomMonster);

Disclaimer: I have no clue what Math.floor(Math.random() * monsters.length) means because I am a complete beginner to javascript (I literally just learned about arrays haha). I just copied it from some other question on this website because of my issue.

I don't know why, but the console always displays "2", which is wasp. And if I were to write console.log(monsters[randomMonster]);, it would just display "wasp". I am really confused, so I was wondering if anyone could explain how Math.floor(Math.random() * monsters.length) even functions? Thank you in advance!




Aucun commentaire:

Enregistrer un commentaire