将随机数组项组合成句子

Combine random array items into sentence

我想做的基本上是使用下面的代码并使其工作,这样我就可以将多个数组中的项目组合成一个句子。因此,例如,现在如果我 运行 这段代码,它将给我 myarray 中的随机项目,即item12 但我想做的是创建几个数组,结果是一个包含(按此顺序)随机项目的句子 来自 array1array2array3 基本上,一个使用数组的随机句子生成器。这个和提议的重复项目之间的区别在于我已经知道如何在单个数组中随机化项目,但想将几个数组项目组合成一个句子结构。 (array1 item) + (array2 item) + (array3 item)

 function GetValue()
{
var myarray= new Array("item1","item2","item3");
var random = myarray[Math.floor(Math.random() * myarray.length)];
document.getElementById("message").innerHTML=random;
}

function GetValue()
{
    var myarray= new Array("item1","item2","item3");
    var random = myarray[Math.floor(Math.random() * myarray.length)];
   document.getElementById("message").innerHTML=random;
}
<input type="button" id="btnSearch" value="Search" onclick="GetValue();" />
<p id="message" ></>

您所要做的就是再创建 2 个数组并执行相同的操作以获取随机单词,然后将它们连接在一起。像这样:

function GetValue() {
  var myarray1 = new Array("item1", "item2", "item3");
  var myarray2 = new Array("item4", "item5", "item6");
  var myarray3 = new Array("item7", "item8", "item9");
  var random1 = myarray1[Math.floor(Math.random() * myarray1.length)];
  var random2 = myarray2[Math.floor(Math.random() * myarray2.length)];
  var random3 = myarray3[Math.floor(Math.random() * myarray3.length)];
  var output = random1 + ' ' + random2 + ' ' + random3;

  document.getElementById("message").innerHTML = output;
}
<input type="button" id="btnSearch" value="Search" onclick="GetValue();" />
<p id="message">
  </>

使用splice:

var myarray= new Array("item1","item2","item3");
while(myarray.length>0){
    var random = myarray.splice(Math.floor(Math.random() * myarray.length));
   document.getElementById("message").innerHTML += ' ' + random;
}

这是DEMO

是这样的吗?

var fragments = [];
fragments.push(["I","You","We","He","She"]);
fragments.push(["called","left","saw","loved","hated"]);
fragments.push(["the","a","some","another"]);
fragments.push(["store","person","rabbit","dog"]);

function getSentence() {
    var sentence = '';
    for (var i=0; i<fragments.length; i++) {
        sentence += fragments[i][Math.floor(Math.random() * fragments[i].length)] + ' ';
    }
    document.getElementById("message").innerHTML = (sentence.trim() + '.');
}
<input type="button" id="btnSearch" value="Search" onclick="getSentence();" />
<p id="message" ></>