如何从字符数组中创建3个唯一值
How to create 3 unique values from an array of characters
你能看一下这个演示,让我知道我如何从数字数组中创建3个唯一的值吗?
var num = [];
var chances = "0123456789";
for (var i = 0; i < 3; i++) {
num.push(chances.charAt(Math.floor(Math.random() * chances.length)));
}
console.log(num);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
你可以这样做
var num = [];
for (var i = 0; i < 3;) {
var ran = Math.floor(Math.random() * 10);
// You can generate random number between 0-9 using this , suggested by @Tushar
if (num.indexOf(ran) == -1)
// check number is already in array
num[i++] = ran;
// if not then push the value and increment i
}
document.write(num.join());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
获取唯一的字母
var res = [],
alp = 'abcdefghijklmnopqrstuvwxyz'.split('');
// creating an array of alphabets for picking alphabers
for (var i = 0; i < 3;) {
var ran = Math.floor(Math.random() * 26);
// You can generate random number between 0-25 using this
if (res.indexOf(alp[ran]) == -1)
// check alphabet is already in array
res[i++] = alp[ran];
// if not then push the value and increment i
}
document.write(res.join());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
或
var res = [],
alp = 'abcdefghijklmnopqrstuvwxyz'.split('');
// creating an array of alphabets for picking alphabers
for (var i = 0; i < 3;) {
var ran = Math.floor(Math.random() * 10000) % 26;
// You can generate random number between 0-25 using this
if (res.indexOf(alp[ran]) == -1)
// check alphabet is already in array
res[i++] = alp[ran];
// if not then push the value and increment i
}
document.write(res.join());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
您也可以试试下面的代码:
var num = [];
var chances = "0123456789";
var len = chances.length;
var str;
while (num.length < 3) {
str = "";
while (str.length < len)
str += chances[Math.floor((Math.random() * len) % len)];
if (-1 === num.indexOf(str))
num.push(str);
}
document.write(JSON.stringify(num));
相关文章:
- onkeyup无法动态创建多个文本区域
- 在页面上创建多个元素,而不是一个发生更改的元素
- sailsjs在创建两个模型时的错误处理
- 使用数据数组创建多个类似组件
- 如何在 Angular JS 中从关联数组创建多个复选框
- 如何在同一浏览器屏幕中创建多个窗口
- Angular.js:使用ng repeat创建2个html容器
- 在新表单上使用JavaScript创建多个共享点项目,但将下一页加载延迟到全部创建
- 日期.GUI创建多个具有相同名称的按钮
- 如何创建多个切换按钮
- 如何创建多个回调
- 创建第一个节点.js插件
- 如何在角度js中以单个形式创建多个组输入类型
- 下划线,需要为数组创建多个顺序
- 在一个页面代码点火器中创建多个分页
- 使用jQuery和CSS创建多个生成的粘性头时出现问题
- Socket.IO和AngularJS创建多个连接,如何停止
- 我想创建4个级联下拉列表
- d3js:创建多个单选按钮
- 在jQuery中创建两个图像之间的行