我的问题是关于我正在处理的报价生成器。它也在onload上工作:),但是当下一个onclick随机选择的报价与上一个显示的报价相同时,我想忽略这种情况。我希望与众不同。谢谢您的提示。
这是我的js代码:
constrctor (private classService: ClassService) {
classService.getContent()
.then(data => 'do whatever you want with tha data');
}
这是工作示例:https://randome-quote-machine.glitch.me
由于我写了下面的波纹管,或者我做错了什么,或者这些答案都不起作用。这是codepen.io的链接,也许有人可以看看并为我提供帮助:https://codepen.io/hubkubas/pen/oPoJba?editors=1010
答案 0 :(得分:1)
您可以将上一个随机索引保留在一个变量中,然后在第二次单击随机化之后,直到新随机数与上一个随机索引不同。
设置一个全局变量,例如let previous = -1
然后:
let random = Math.floor(Math.random() * quotes.length);
while(previous == random)
{
random = Math.floor(Math.random() * quotes.length)
}
previous = random
var newInitialQuote = quotes[random];
答案 1 :(得分:0)
也许您可以在数据中添加一个is_showed标记:
var quotes = [
{
showed: false,
text: "Memento mori",
autor: "Bractwo Męki Pańskiej"
},
{
showed: false,
text: "Jeśli możesz sobie coś wymarzyć, możesz też to zrobić.",
autor: "Walt Disney"
},
{
showed: false,
text: "Wszystko jest możliwe. Niemożliwe wymaga po prostu więcej czasu.",
autor: "Dan Brown"
},
{
showed: false,
text: "Czerp z innych, ale nie kopiuj ich. Bądź SOBĄ",
autor: "Michel Quois"
},
{
showed: false,
text: "Kiedy łamiesz zasady, łam je mocno i na dobre.",
autor: "Terry Pratchett"
}
];
window.onload = function() {
quoteMachine.initialQuote()
};
var quoteMachine = {
initialQuote: function(next) {
var rand_number = Math.floor(Math.random() * quotes.length);
var newInitialQuote = quotes[rand_number];
if (newInitialQuote.showed) {
var next = -1;
for (var i = 0; i < quotes.length; i++) {
if (quotes[next].showed == false) {
break;
}
}
if (next == -1) {
document.getElementById("new-quote").innerHTML = "Sorry I have not new quotes";
document.getElementById("autor").innerHTML = "John Doe";
return;
}
rand_number = next;
newInitialQuote = quotes[rand_number];
}
quotes[rand_number].showed = true;
var newInitialQuoteText = newInitialQuote.text;
var newInitialQuoteAutor = newInitialQuote.autor;
document.getElementById("new-quote").innerHTML = newInitialQuoteText;
document.getElementById("autor").innerHTML = newInitialQuoteAutor;
}
};