首页 > 解决方案 > 你怎么不会从 math.floor 得到重复的数字?

问题描述

我的目标是让这些宝石都有 1-10 的不同值

如果你能在仍然使用 mathfloor 的同时帮助我,我也会很感激

//Variables
var emGem = 0;
var ruGem = 0;
var diGem = 0;
var saGem = 0;
var possibleGem = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

//Initiate scores
emGem = possibleGem[Math.floor(Math.random() * possibleGem.length)];
ruGem = possibleGem[Math.floor(Math.random() * possibleGem.length)];
diGem = possibleGem[Math.floor(Math.random() * possibleGem.length)];
saGem = possibleGem[Math.floor(Math.random() * possibleGem.length)];

//Debug
console.log(emGem);
console.log(ruGem);
console.log(diGem);
console.log(saGem);
console.log(randomNumber);

标签: javascriptjqueryarraysrandom

解决方案


您需要找到一种无需替换即可选择元素的方法。您可以选择一个随机索引,然后选择该索引splice处的元素以获取该元素,同时将其从数组中删除:

var possibleGem = [1,2,3,4,5,6,7,8,9,10];

const randItem = () => {
  const randIndex = Math.floor(Math.random() * possibleGem.length);
  return possibleGem.splice(randIndex, 1)[0];
};

const emGem = randItem();
const ruGem = randItem();
const diGem = randItem();
const saGem = randItem();

//Debug
console.log(emGem);
console.log(ruGem);
console.log(diGem);
console.log(saGem);


推荐阅读