javascript - 你怎么不会从 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);
解决方案
您需要找到一种无需替换即可选择元素的方法。您可以选择一个随机索引,然后选择该索引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);
推荐阅读
- bash - bash 脚本卡在 for 循环的末尾
- java - 尝试从 UI 中添加 SQL 语句时,Struts2 应用程序错误输出为未定义操作
- postgresql - 如何选择某些列具有超过 1 个不同值的行?
- r - ggplot2中组之间的图表差异
- javascript - 删除特定的数组元素,而不仅仅是最后一个 .pop - Redux-form
- ubuntu - Ubuntu 构建依赖项 - libblas
- pycharm - 如何设置光标显示在 Pycharm 输出的行尾?
- arrays - 如何从返回的数组中删除具有 nil 值的额外数组级别
- netbeans - 删除 netbeans 8.2 中的黄色括号突出显示
- c# - 重用具有多个属性的一种方法