2016-08-11 60 views
2

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

回答

1

是不是隻是concat使這非常混亂?你可以這樣做:

content = r(person) + " " + r(verb) + "ed " + r(person) + ", so " 
    + r(person) + " is " + r(verb) + "ing " + r(person); 

你也可以使用一個數組加盟,這是還挺不錯,因爲你可以將你想要的元素之間的任何字符,你可以使用推()來構建陣列。

content = [r(person), " ", r(verb), "ed ", r(person), " 
    , so ", r(person), " is ", r(verb), "ing ", r(person)]; 

content = content.join(""); 
+1

其實你可以加入的空格字符,並且會幫助你清理,甚至不需要某些數組條目也只是空的空間! – spozun

0

document.querySelector("button").addEventListener('click', function() { 
 
    var person = ["Grace", "Jared", "Suzy", "Tommy"]; 
 
    var verb = ["answer", "ask", "block", "call", "delay", "expect", "follow", "greet", "help", "inform", "join", "kick", "label", "mark", "need", "order", "pick", "question", "request", "signal", "trick", "visit", "warn"]; 
 
    document.getElementById("output").innerHTML = [r(person), r(verb) + "ed", r(person) + ", so", r(person), "is", r(verb) + "ing", r(person) + "."].join(" "); 
 
}); 
 

 
function r(list) { 
 
    return list.splice(Math.floor(Math.random() * list.length), 1)[0]; 
 
};
<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet"/> 
 
<div class="container"> 
 
    <button>Go</button> 
 
    <div id="output"></div> 
 
</div>

0

另一種方法是使用一個模板,如:

"[P] [V]ed [P], so [P] is [V]ing [P]" 

,並使用.replace()方法使用自定義的回調函數:

var person = [ 
 
     "Grace", "Jared", "Suzy", "Tommy" 
 
    ], 
 
    verb = [ 
 
     "answer", "ask", "block", "call", 
 
     "delay", "expect", "follow", "greet", 
 
     "help", "inform", "join", "kick", 
 
     "label", "mark", "need", "order", 
 
     "pick", "question", "request", "signal", 
 
     "trick", "visit", "warn" 
 
    ]; 
 

 
var template = "[P] [V]ed [P], so [P] is [V]ing [P]"; 
 

 
var str = template.replace(/\[([PV])\]/g, function(m, p0) { 
 
    var list = {'P': person, 'V': verb}[p0]; 
 
    return list.splice((Math.random() * list.length) | 0, 1); 
 
}); 
 

 
console.log(str);

0

一種不同的方法/執行你的代碼,只是作爲一個inpsiration:

//takes an Array, shuffles it in place (no copy), and returns the shuffled Array 
function shuffle(arr){ 
    for(var len = arr.length, i=len, j, tmp; i--;){ 
     j = Math.floor(Math.random() * (len-1)); 
     if(j>=i) ++j; 
     tmp = arr[j]; 
     arr[j] = arr[i]; 
     arr[i] = tmp; 
    } 
    return arr; 
} 

//a utility to uppercase only the first-char of a string 
function uppercaseFirstChar(str){ 
    return str.charAt(0).toUpperCase() + str.slice(1); 
} 

//stringpool, 
//the code never mutates this, so there's no need to ever reset it. 
var strings = {//TODO: find a better name(space) than `strings` 
    persons: [ 
     "Grace", "Jared", "Suzy", "Tommy" 
    ], 

    verbs: [ 
     "answer", "ask", "block", "call", 
     "delay", "expect", "follow", "greet", 
     "help", "inform", "join", "kick", 
     "label", "mark", "need", "order", 
     "pick", "question", "request", "signal", 
     "trick", "visit", "warn" 
    ] 
} 

//keep the tasks simple and clear. 
//this function builds and returns a random sentence. 
//no more, no less. 
//it doesn't need to know what the result is used for 
function randomSentence(){ 
    //don't mutate the string-pool, create a copy of the Arrays, and shuffle that 
    var person = shuffle(strings.persons.slice()); 
    var verb = shuffle(strings.verbs.slice()); 

    //build the sentence, uppercase the first char, and return the result 
    return uppercaseFirstChar(
     `${person[0]} ${verb[0]}ed ${person[1]}, so ${person[2]} is ${verb[1]}ing ${person[3]}` 
    }; 


    //an example how you can reference the same person/verb multiple times in the same result 
    //your r(array)-approach is not able to that; it's kind of destructive. 
    //return `${person[0]} ${verb[0]}ed ${person[1]}; ${person[1]} has been ${verb[0]}ed by ${person[0]}` 
}; 


document.getElementById("button").onclick = function() { 
    document.getElementById("output").innerHTML = randomSentence(); 
};