joshcawthorne joshcawthorne - 3 months ago 11
HTML Question

Generate random var and then detect it using JavaScript

I'm working on a small project, where I would like to generate a random var based from multiple strings, and then further down choose another string based on the random var for earlier.

I'm not 100% if I've explained it perfectly, but I've created a sample version of the code below. I should state that in the actual code, there's close to 50 entries, rather than 3.

var fruits=['Apples','Bannanas','Pears']

var veg=['Potatoes','Carrots','Peas']

var fruitInfo=['This is an Apple','This is a Bannana','This is a pear']

fruit.innerHTML+=fruits[Math.round(Math.random()*(fruits.length-1))]+'\n';

veg.innerHTML+=veg[Math.round(Math.random()*(veg.length-1))]+'\n';


So, if it's unlear, I want to detect if an Apple has been selected and then state "This is an Apple" etc. I've also added in veg as there will be other random factors, however they won't need to be detected.

Any help would be greatly appreciated!

Answer

Looks like you need to create the random value and save in a variable to use it repeatedly. And create another one for veggies (as I suppose you want different random for that).

    var fruits=['Apples','Bannanas','Pears']
    var veg=['Potatoes','Carrots','Peas']
    var fruitInfo=['This is an Apple','This is a Bannana','This is a pear']
    var random_num = Math.floor(Math.ran‌​dom()*fruits.length)
    fruit.innerHTML+=fruits[random_num]+'\n';
    fruitInfo.innerHTML+=fruitInfo[random_num]+'\n';
    var random_num2 = Math.floor(Math.ran‌​dom()*veg.length)
    veg.innerHTML+=veg[random_num2]+'\n';
Comments