I am trying to take a set of words for example...
Apple
Banana
The
Orange
House
Boat
Lake
Car
And
I want to be able to output 50 of these words at random to a div using javascript. Is this possible and if so should I be looking at putting them into an array or something similar?
I am trying to take a set of words for example...
Apple
Banana
The
Orange
House
Boat
Lake
Car
And
I want to be able to output 50 of these words at random to a div using javascript. Is this possible and if so should I be looking at putting them into an array or something similar?
Share Improve this question asked Sep 7, 2012 at 10:42 fightstarr20fightstarr20 12.7k45 gold badges171 silver badges301 bronze badges 1- Of course this is possible. Start with an array ... and if you have any specific problem, you can e back to us. – devnull69 Commented Sep 7, 2012 at 10:47
4 Answers
Reset to default 2Yes, that's possible, using the Math.random
function to generate the text and innerHTML
to fill a div.
The array make it easier to get the words.
var tokens = ['Apple', 'Banana', 'The' ...];
var text = '';
for (var i=0; i<50; i++) {
text += tokens[Math.floor(Math.random()*tokens.length)];
}
document.getElementById('myDiv').innerHTML = text;
Yes, use an array. To get a random word from such an array, use the following:
function getRandomWord() {
var words = ['Apple','Banana','The','Orange','House','Boat','Lake','Car','And'];
return words[Math.floor(Math.random() * words.length)];
}
Then invoke that function to whatever extent you like.
var paragraph = [];
for(var i = 0; i < 50; i++)
paragraph.push(getRandomWord());
$('#my-container').text( paragraph.join(' ') );
That's possible and here is a quick and dirty example of it. (Sorry I've got no more time atm)
var words = ['apple', 'beer', 'cake', 'potato', 'orange'],
div = document.getElementById('foo');
for(i = 0; i < 50; i++) {
div.innerHTML += ' ' + words[Math.floor(Math.random() * words.length)];
}
http://jsfiddle/LavY5/
Yes, put all your words in an Array
. Then apply the Fisher-Yates shuffle algorithm, to shuffle/randomize your words array. Then, take a slice
of the array of your specified size, and print those words to the HTML:
var words = [ "Apple", "Banana", "The", "Orange", "House", "Boat", "Lake", "Car", "And" ];
function fisherYates (arr) {
var n = arr.length;
while (n) {
var j = Math.floor(Math.random() * n--);
var temp = arr[n];
arr[n] = arr[j];
arr[j] = temp;
}
return arr;
}
fisherYates(words); // shuffle
var randomParagraph = words.slice(0, 5).join(" "); // take 5 random words
document.write(randomParagraph);
DEMO.