数组的随机数,但不相同| JavaScript

Random numbers for array, but not the same | JavaScript

本文关键字:JavaScript 随机数 数组      更新时间:2023-09-26

我正在尝试创建一个数字数组。数组应该像下面这样:

[1, 2, 1][2, 1, 2]

我不想再选择相同的数字。

我不想要[1, 1, 2][2, 2, 1]

我有以下代码:

var chosenHosts = [];
for (var i = 0; i < match.match_games; ++i) {
     var num = 1 + Math.floor(Math.random() * 2);
     chosenHosts.push(num);
}
console.log(chosenHosts);

这段代码两次推送同一个数字。有人知道如何实现上述目标吗?

注:很抱歉,我不知道该如何描述它

这样就可以了

var chosenHosts = [1 + Math.floor(Math.random() * 2)];
for (var i = 1; i <  match.match_games; i++) {
     var num = chosenHosts[i - 1] == 1 ? 2 : 1; 
     chosenHosts.push(num);
}
console.log(chosenHosts);

您可以检查数组中的最后一个元素,并继续创建随机数,直到它不同。

var chosenHosts = [1 + Math.floor(Math.random() * 2)];
for (var i = 0; i < match.match_games; i++) {
  var r = 1 + Math.floor(Math.random() * 2);
  while (chosenHosts[i] == r)
    r = 1 + Math.floor(Math.random() * 2);
  chosenHosts.push(r);
}
console.log(chosenHosts);