【问题标题】:How to be sure that the next randomly selected value from an array is not the same as the current one using Javascript? [duplicate]如何确保从数组中随机选择的下一个值与使用 Javascript 的当前值不同? [复制]
【发布时间】:2022-01-24 03:33:35
【问题描述】:

我从数组中随机选择值。我想确定下一个选定的值与当前的值不同。如何在 Javascript 中实现此规则?

const pages = [1, 2, 3, 4, 5];
const random = Math.floor(Math.random() * pages.length);
console.log(pages[random]);

【问题讨论】:

  • 什么是“当前”?这段代码是如何调用/使用的?

标签: javascript arrays random


【解决方案1】:

您可以过滤页面删除当前值,然后再选择随机元素。

【讨论】:

    【解决方案2】:

    如果你选的和之前的一样,就选一个新的:

    const pages = [1, 2, 3, 4, 5];
    const random = Math.floor(Math.random() * pages.length);
    console.log(pages[random]);
    
    let random2;
    // Pick a new one:
    while (random == ( random2 = Math.floor(Math.random() * pages.length)));
    

    这假定数组中的每个值都不同,因此它只关心两个索引(randomrandom2)是否不同。

    【讨论】:

      猜你喜欢
      • 2011-08-08
      • 2018-01-13
      • 2011-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多