将数组中的两个随机单词组合,然后将单词连接成一个单词

时间:2012-08-24 22:40:46

标签: jquery arrays string random

我有一个数组中的单词列表,我正在尝试输出单词以生成一个单词,

示例将是我的数组中的单词“one”,“two”,“three”,“four”,我会

希望输出可能是:

onethree或fourtwo,或onefour等...

任何帮助都会很棒!这是我到目前为止,但可以使它正确执行

$(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(", "));

});

感谢高级!

1 个答案:

答案 0 :(得分:1)

如果我理解你的问题,你应该使用这样的东西:

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/