如何从一个字符数组创建3个唯一值

时间:2015-10-06 05:25:11

标签: javascript

请你看一下这个演示,让我知道如何从一组数字中创建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>

2 个答案:

答案 0 :(得分:2)

你可以做这样的事情

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>

答案 1 :(得分:0)

您也可以尝试以下代码:

&#13;
&#13;
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));
&#13;
&#13;
&#13;