Javascript - 生成一个没有重复数字的randome 4位数字

ill*_*ode 4 javascript random math

我有这个功能来创建一个随机的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("")) ;
    }
Run Code Online (Sandbox Code Playgroud)

但我需要创建一个没有重复数字的4位数随机数.所以"1234"或"9673"......但不是"1145"或"5668"

任何帮助都是非常感谢的人!不确定有效的方式来实现这个目标

ble*_*lex 5

您可以使用这个方便的shuffle函数来混洗包含数字的数组,并选择前4个.

function random4Digit(){
  return shuffle( "0123456789".split('') ).join('').substring(0,4);
}

function shuffle(o){
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
}

alert( random4Digit() );
Run Code Online (Sandbox Code Playgroud)

编辑:如果您确实想要一个不以0开头的数字:

function random4DigitNumberNotStartingWithZero(){
    // I did not include the zero, for the first digit
    var digits = "123456789".split(''),
        first = shuffle(digits).pop();
    // Add "0" to the array
    digits.push('0');
    return parseInt( first + shuffle(digits).join('').substring(0,3), 10);
}

function shuffle(o){
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
}

alert( random4DigitNumberNotStartingWithZero() );
Run Code Online (Sandbox Code Playgroud)