请问如何从1~10中随机读取不重复的6个数字
发布于 6 年前 作者 czhong 11885 次浏览 来自 官方Issues
  • 需求的场景描述(希望解决的问题)

请问如何从1~10之间读取6个随机不重复的数字?

  • 希望提供的能力
3 回复

Math.floor((Math.random()*9+1)*100000)

let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
array.sort(function() {
  return 0.5 - Math.random();
})
let result = array.slice(0, 6);
console.log(result);

数组打乱顺序后取前六位即可。

显示出来是有重复的,如何做到不重复呢 

Page({

data: {

code: “”

},

getcode: function () {

this.createCode();

},

createCode() {

var code;

//首先默认code为空字符串

code = ‘’;

//设置长度5

var codeLength = 5;

//设置随机字符

var random = new Array(‘1,’, ‘2,’, ‘3,’, ‘4,’, ‘5,’, ‘6,’, ‘7,’, ‘8,’, ‘9,’, ‘10,’);

//循环codeLength

for (var i = 1; i < codeLength; i++) {

//设置随机数范围1 ~ 10

var index = Math.floor(Math.random() * 10);

//字符串拼接

code += random[index];

}

//将拼接好的字符串赋值

this.setData({

code: code

})

},

})

回到顶部