随机侮辱生成器(随机化结果)

Random Insult Generator (Randomizing Results)

我写了一个随机侮辱生成器。很好,并且可以很好地满足我的需要。问题是,当我 运行 程序不止一次时,每次的侮辱都是一样的,除非我再次复制所有变量。这是我的代码:

var bodyPart = ["face", "foot", "nose", "hand", "head"];
var adjective = ["hairy and", "extremely", "insultingly", "astonishingly"];
var adjectiveTwo = ["stupid", "gigantic", "fat", "horrid", "scary"];
var animal = ["baboon", "sasquatch", "sloth", "naked cat", "warthog"];

var bodyPart = bodyPart[Math.floor(Math.random() * 5)];
var adjective = adjective[Math.floor(Math.random() * 4)];
var adjectiveTwo = adjectiveTwo[Math.floor(Math.random() * 5)];
var animal = animal[Math.floor(Math.random() * 5)];

var randomInsult = "Your" + " " + bodyPart + " " + "is more" + " " + adjective + " " + adjectiveTwo + " " + "than a" + " " + animal + "'s" + " " + bodyPart + ".";

randomInsult;
"Your nose is more insultingly stupid than a warthog's nose."
randomInsult;
"Your nose is more insultingly stupid than a warthog's nose."

我想做的是当我再次 运行 randomInsult; 时,我想要一个不同的结果。

使用函数:

function generateRandomInsult() {
    // ... all of your existing code ...

    return randomInsult;
}

generateRandomInsult();      // this is what you repeat each time

根据我上面的评论,你需要使用一个函数。

var bodyPart = ["face", "foot", "nose", "hand", "head"];
var adjective = ["hairy and", "extremely", "insultingly", "astonishingly"];
var adjectiveTwo = ["stupid", "gigantic", "fat", "horrid", "scary"];
var animal = ["baboon", "sasquatch", "sloth", "naked cat", "warthog"];

var randomInsult = (function() {
  var bp, a, a2, an;
  var bp = bodyPart[Math.floor(Math.random() * 5)];
  var a = adjective[Math.floor(Math.random() * 4)];
  var a2 = adjectiveTwo[Math.floor(Math.random() * 5)];
  var an = animal[Math.floor(Math.random() * 5)];
  var insult = "Your" + " " + bp + " " + "is more" + " " + a + " " + a2 + " " + "than a" + " " + an + "'s" + " " + bp + ".";

  alert(insult);
});

document.getElementById('test').addEventListener('click', randomInsult, false);
<button id="test">Click me</button>

您必须在每次调用时对 select 随机 bodyPart、形容词、adjectiveTwo 和动物执行类似的操作。

function randomInsult() {
    var bodyPart = ["face", "foot", "nose", "hand", "head"];
    var adjective = ["hairy and", "extremely", "insultingly", "astonishingly"];
    var adjectiveTwo = ["stupid", "gigantic", "fat", "horrid", "scary"];
    var animal = ["baboon", "sasquatch", "sloth", "naked cat", "warthog"];
    var bodyPart = bodyPart[Math.floor(Math.random() * 5)];
    var adjective = adjective[Math.floor(Math.random() * 4)];
    var adjectiveTwo = adjectiveTwo[Math.floor(Math.random() * 5)];
    var animal = animal[Math.floor(Math.random() * 5)];
    return "Your" + " " + bodyPart + " " + "is more" + " " + adjective + " " + adjectiveTwo + " " + "than a" + " " + animal + "'s" + " " + bodyPart + ".";
}

在您的代码中,您只生成了一次 "randomInsult" 字符串。它需要在每次调用时生成,并带有新的随机值。 因此,只需将您的代码嵌入到函数中即可。

这样称呼它:

randomInsult();