我想创建一个生成器,基于从随机确定的索引处的不同单词的数组中提取变量来创建半随机语句,然后从数组中删除该单词以确保没有重复。压缩JavaScript随机语句生成器代码
它的工作原理,但不是容易建立的方式。每次我想从已经从同一行中拉出的数组中拉出时,脚本就会停止。
document.getElementById("button").onclick = function() {
genContent();
};
function genContent() {
\t var content = "";
\t lists();
// --- what works ---
content += r(person).concat(" ", r(verb), "ed ");
content += r(person).concat(", so ");
content += r(person).concat(" is ", r(verb), "ing ");
content += r(person);
// --- what I want to condense it down to ---
// content += r(person).concat(" ", r(verb), "ed ", r(person), ", so ", r(person), " is ", r(verb), "ing ", r(person));
document.getElementById("output").innerHTML = content.charAt(0).toUpperCase() + content.slice(1);
};
function r(array) {
random = Math.floor(Math.random() * array.length);
value = array[random];
array.splice(random, 1);
return value;
};
function lists() {
\t person = ["Grace", "Jared", "Suzy", "Tommy"];
verb = [
\t "answer", "ask", "block", "call",
"delay", "expect", "follow", "greet",
"help", "inform", "join", "kick",
"label", "mark", "need", "order",
"pick", "question", "request", "signal",
"trick", "visit", "warn"];
};
<div>
<textarea id="output" output="" rows="8" style="width:50%; min-width:285px;" readonly="readonly">
Click the button to generate a sentence.
</textarea>
<br>
<input type="button" value="Make content" id="button">
</div>
(jsfiddle link because it's easier to edit)
如何实现沿的注释掉的代码(第15行)线的东西任何想法?
其实你可以加入的空格字符,并且会帮助你清理,甚至不需要某些数组条目也只是空的空间! – spozun