【问题标题】:How to create 3 unique values from an array of characters如何从字符数组中创建 3 个唯一值
【发布时间】:2015-10-06 05:25:10
【问题描述】:

您能否看一下这个演示并告诉我如何从一个数字数组中创建 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);
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

【问题讨论】:

标签: javascript


【解决方案1】:

你可以这样做

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());
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

为了获得独特的字母

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());
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

或者

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());
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

  • 谢谢 Pranav C Balan,你能告诉我锄头也能从字母表中获得 3 个独特的字母吗?
  • 这是一个很好的解决方法@Behseini,但请记住this does not generate random unique numbers, this'll just pick unique numbers from random numbers
  • @Behseini 您无法生成唯一的随机数。
  • 好的,我想我明白你现在在说什么了
【解决方案2】:

你也可以试试这个代码:

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));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 2016-01-17
    相关资源
    最近更新 更多