我写了一个随机的侮辱发生器。它很好,适合我需要的东西。问题是当我不止一次运行程序时,每次都会发生侮辱,除非我再次复制所有变量。这是我的代码:
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;
时,我想要一个不同的结果。
答案 0 :(得分:0)
使用功能:
function generateRandomInsult() {
// ... all of your existing code ...
return randomInsult;
}
generateRandomInsult(); // this is what you repeat each time
答案 1 :(得分:0)
根据我上面的评论,你需要使用一个函数。
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>
&#13;
答案 2 :(得分:0)
你必须做这样的事情,在每次电话会议中选择一个随机的bodyPart,形容词,形容词和动物。
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();