0

我有一个数组中的单词列表,我试图输出单词来组成一个单词,

示例是我的数组中的单词“一”、“二”、“三”、“四”,我会

希望输出可能是:

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

});

提前致谢!

4

1 回答 1

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/

于 2012-08-25T16:24:33.233 回答