我有一个数组中的单词列表,我正在尝试输出单词以生成一个单词,
示例将是我的数组中的单词“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(", "));
});
感谢高级!
答案 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;
}