Reputation: 13
How do I pull a string randomly from an array, and insert that string into a span? Heres the arrays:
var startupX = ['Uber', 'Google', 'Amazon', 'Apple', 'Facebook', 'Twitter'];
var startupY = ['Slack', 'Trello', 'Tesla', 'Hyperloop', 'Harvest'];
And these are the spans that a startup name needs to go into
<h1 id="xForY"></h1>
<h1>A startup that is
<span id="startupX"></span>, but for
<span id="startupY"></span>
</h1>
Upvotes: 1
Views: 421
Reputation: 100331
Math.random
will give you a number from 0 inclusive to 1 exclusive [0, 1)
.
You can use that to get a random number that is within the max array index:
var randomIndex = Math.floor(Math.random() * startupX.length);
Then you can use this index to access your array:
startupX[randomIndex];
Having the value you can place it on the element:
document.getElementById('startupX').innerHTML = startupX[randomIndex];
Upvotes: 1
Reputation: 42460
First, find a random element from each of the arrays. Math.random()
will help you with that.
Then you can use the DOM API to insert it into your page:
var startupX = ['Uber', 'Google', 'Amazon', 'Apple', 'Facebook', 'Twitter'];
var startupY = ['Slack', 'Trello', 'Tesla', 'Hyperloop', 'Harvest'];
var x = startupX[Math.floor(Math.random()*startupX.length)];
var y = startupY[Math.floor(Math.random()*startupY.length)];
document.getElementById('startupX').innerHTML = x;
document.getElementById('startupY').innerHTML = y;
<h1 id="xForY"></h1>
<h1>A startup that is
<span id="startupX"></span>, but for
<span id="startupY"></span>
</h1>
Upvotes: 1