压缩JavaScript随机句生成器代码

时间:2016-08-11 20:07:20

标签: javascript random

我正在尝试创建一个基于从随机确定的索引处的不同单词数组中拉出变量的半随机句子,然后从数组中删除该单词以确保没有重复。 / p>

它有效,但不是很容易建立起来的。每当我想从已经从同一行中拉出的数组中拉出时,脚本就会停止。

document.getElementById("button").onclick = function() {
  genContent();
};

function genContent() {
	var content = "";
	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() {

	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"];
};
<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行)实现某些目标的任何想法?

4 个答案:

答案 0 :(得分:1)

只是因为concat使这个非常混乱?你可以这样做:

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

你也可以使用一个数组连接,这有点好,因为你可以在元素之间插入你想要的任何字符,你可以使用push()来构建数组。

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

content = content.join("");

答案 1 :(得分:0)

&#13;
&#13;
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];
};
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分: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);

答案 3 :(得分: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();
};