我想創建一個生成器,基於從隨機確定的索引處的不同單詞的數組中提取變量來創建半隨機語句,然後從數組中刪除該單詞以確保沒有重複。壓縮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