javascript - Math.random避免相同的结果,如何防止代码忽略条件语句?

标签 javascript

您好,所以我一直在尝试让我的藤蔓生成器在您每次运行时生成随机藤蔓。我正在努力让最后 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/

相关文章:

javascript - jquery 自动完成验证输入的值

javascript - 从数组中删除一个对象?

javascript - 加载页面上带有 Canvas 的 XMLHttpRequest

javascript - jQuery。 .load() 不会给出响应/状态

javascript - 应用 css 比例转换后,Extjs 组合框不起作用

javascript - Jquery 来检查复选框仅在您第一次单击它时起作用

javascript - 兼容 ES6 功能

javascript - 使用 Scrapy 获取 JavaScript 函数的参数

javascript - 构建大型前端元素的最佳方式是什么?

javascript - Sails.js - 文件上传