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

Random Insult Generator (Randomizing Results)

本文关键字:随机化 结果 随机      更新时间:2023-09-26

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

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>

你必须做这样的事情来选择随机的bodyPart,形容词,形容词Two和动物在每次调用。

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();