【发布时间】:2021-10-23 10:29:16
【问题描述】:
我有这个函数来创建一个随机的 4 位数字:
generateCode = function(){
var fullNumber = [];
var digit1 = Math.floor(Math.random() * 9) + 1;
var digit2 = Math.floor(Math.random() * 9) + 1;
var digit3 = Math.floor(Math.random() * 9) + 1;
var digit4 = Math.floor(Math.random() * 9) + 1;
fullNumber.push(digit1, digit2, digit3, digit4);
this.theCode(fullNumber.join("")) ;
}
但我需要创建一个没有重复数字的 4 位随机数。
所以“1234”或“9673”。但不是“1145”或“5668”
有没有有效的方法来做到这一点?
【问题讨论】:
-
一种简单的方法:将所有数字放在一个数组中,随机排列顺序,然后从数组中选出前 4 个数字:stackoverflow.com/questions/2450954/…
标签: javascript math random