【问题标题】:Combine two random words in array then join words into one word将两个随机单词组合在数组中,然后将单词连接成一个单词
【发布时间】:2012-08-20 11:57:21
【问题描述】:

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

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

希望输出可能是:

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

});

感谢高级!

【问题讨论】:

  • 无法重现您的问题.. 看看这段代码:jsfiddle.net/dFJ5E
  • 您能否详细说明预期的输出?
  • 它在数组中取一个随机字符串并合并为一个单词。所以输出可能是:“twothree”“onefour”“sixone”

标签: jquery arrays string random


【解决方案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/

【讨论】:

    猜你喜欢
    • 2020-08-30
    • 2018-03-30
    • 2017-11-03
    • 1970-01-01
    • 2011-04-16
    • 1970-01-01
    • 2019-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多