您好,所以我一直在尝试让我的藤蔓生成器在您每次运行时生成随机藤蔓。我正在努力让最后 3 根藤蔓永远不会重复出现。
请注意,我只想检查最后 3 个要避开的藤蔓。
var vines = [
['https://www.youtube.com/watch?v=21yI4dtAyJQ', 'Gotta love dogs'],
['https://www.youtube.com/watch?v=MB1Ud95U8FE', 'The struggle of measuring something without measuring tape'],
['https://www.youtube.com/watch?v=b6l63-AdU6Y', 'When the cars full but u still tryna roll with the squad'],
['https://www.youtube.com/watch?v=19KOD8-mGm4', 'When the pool water is too cold..'],
['https://www.youtube.com/watch?v=05Bf5vs8j9Q', 'Can I please get a waffle?'],
['https://www.youtube.com/watch?v=2IekMo_DQmw', 'Cheese of truth']
];
var random = Math.floor((Math.random() * vines.length) + 0);
var prev = [];
function Scramble(number, last) {
if(last.includes(number)) {
Scramble(random, prev); // If the previous number matches current rerun function for a new number.
}
if(last.length === 3) {
last.pop(); // Removes the 3rd vine to make room for a new one.
}
last.unshift(number); // Register the last given number.
console.log(`[${number+1}] ${vines[number][1]}\n${vines[number][0]}`)
}
Scramble(random, prev);
最佳答案
调用Scramble(random, prev);
函数时需要更新随机数。调用 Scramble(random, prev);
后,您需要从函数返回。
请检查代码
var vines = [
['https://www.youtube.com/watch?v=21yI4dtAyJQ', 'Gotta love dogs'],
['https://www.youtube.com/watch?v=MB1Ud95U8FE', 'The struggle of measuring something without measuring tape'],
['https://www.youtube.com/watch?v=b6l63-AdU6Y', 'When the cars full but u still tryna roll with the squad'],
['https://www.youtube.com/watch?v=19KOD8-mGm4', 'When the pool water is too cold..'],
['https://www.youtube.com/watch?v=05Bf5vs8j9Q', 'Can I please get a waffle?'],
['https://www.youtube.com/watch?v=2IekMo_DQmw', 'Cheese of truth']
];
var random = Math.floor((Math.random() * vines.length) + 0);
var prev = [];
function Scramble(number, last) {
// console.log(number);
if(last.includes(number)) {
random = Math.floor((Math.random() * vines.length) + 0);
Scramble(random, prev);
return;
}
if(last.length === 3) {
last.pop(); // Removes the 3rd vine to make room for a new one.
}
last.unshift(number); // Register the last given number.
console.log(`[${number+1}] ${vines[number][1]}\n${vines[number][0]}`)
}
Scramble(random, prev);
关于javascript - Math.random避免相同的结果,如何防止代码忽略条件语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49642837/