Reputation: 3520
I have a list of words in an array and I am trying to output the words to make one word,
Example would be the words "one", "two", "three", "four" in my Array and I would
want the output possibly to be:
onethree or fourtwo, or onefour, etc...
Any help would be awesome! This is what I have so far but can get it to perform correctly
$(document).ready( function() {
var randomtxt = [
"ONE","TWO","THREE",
"FOUR","FIVE","SIX","SEVEN"
];
var randomIndex = Math.floor(Math.random() * randomtxt.length);
var randomElement = randomtxt[randomIndex];
$('#text-content').text(randomElement + randomtxt.join(", "));
});
Thanks in Advanced!
Upvotes: 0
Views: 1939
Reputation: 9424
If I understand your problem correctly, then you should use something like this:
var words = [ "one", "two", "three", "four", "five", "six", "seven" ];
$( "#text-content" ).text( createNewWord( words ) );
function getRandomWord( wordsArray ) {
var index = Math.floor( Math.random() * wordsArray.length );
return wordsArray[index];
}
function createNewWord( wordsArray ) {
var newWordPart1 = getRandomWord( wordsArray );
var newWordPart2 = getRandomWord( wordsArray );
// this will prevent new words like oneone twotwo, etc.
// if you want the repeated words, just remove this while entirely
while ( newWordPart2 == newWordPart1 ) {
newWordPart2 = getRandomWord( wordsArray );
}
return newWordPart1 + newWordPart2;
}
jsFiddle: http://jsfiddle.net/davidbuzatto/UwXHT/
Upvotes: 1