繁体   English   中英

您如何不从math.floor获得重复数字?

[英]How do you not get repeating numbers from 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); 

感谢大家! 我用您所有的答案来思考如何自己写这篇文章,因为你们正在使用我还没有学过的东西,但是我一定会检查出来的! 如果您对我决定如何做感兴趣,那就是。

 while (true) { 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)]; if (emGem !== ruGem && emGem !== diGem && emGem !== saGem && ruGem !== diGem && ruGem !== saGem && diGem !== saGem) { break; }} 

我会制造一系列可能的宝石,然后将其洗牌。 每当我需要一个值时,我都会将其从数组中弹出。

shuffleArray()代码来自如何随机化(随机播放)JavaScript数组?

 //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]; shuffleArray(possibleGem); //Initiate scores emGem = possibleGem.pop(); ruGem = possibleGem.pop(); diGem = possibleGem.pop(); saGem = possibleGem.pop(); //Debug console.log(emGem); console.log(ruGem); console.log(diGem); console.log(saGem); function shuffleArray(array) { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; // eslint-disable-line no-param-reassign } } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM