我似乎无法在过去和当前相同时重复这一点(这是一个新的报价生成器)。
function random() { // random number 0-9
var number = Math.floor(Math.random() * 9);
return number;
}
var past = [0]; // array of past quotes
function writer() { // on button click for new random quote
var current = random();
past.push(current);
function checker() {
if (past[past.length - 2] === past[past.length - 1]) {
current = random();
checker();
}
}
checker();
}
答案 0 :(得分:0)
Rekursiv geht meistens schief (抱歉没有英语)
如果条件为真,则未更改最后一个值:
var past = [-1]; // impossible value;
function writer() { // on button click for new random quote
var current = random(); // get a first random
past.push(current); // add this to past array
function checker() {
// check last two values
if (past[past.length - 2] === past[past.length - 1]) {
current = random(); // if equal, get a new random;
checker(); // re-call - BUT -
// as there' actually no change to past,
// we're in an infinite loop.
}
}
checker();
}
变化:
var past = [-1]; // impossible value;
function writer() { // on button click for new random quote
var current = random(); // get a first random
past.push(current); // add this to past array
function checker() {
// check last two values
if (past[past.length - 2] === past[past.length - 1]) {
current = random(); // if equal, set a new random even to past
past[past.length - 1] = current;
checker(); // re-call
}
}
checker();
}