skip to Main Content

My HTML page has a script to generate a random code of 8 characters (capital letters and numbers). It works like this, I refresh the page via F5 and the new code appears on the page. Sometimes, when generating, I get an "undefined" error instead of a single character. Help fix this. Below is my script.

function generate(len,type)
{
   var ints =[0,1,2,3,4,5,6,7,8,9]; 
   var chars=['A','B','C','D','E','F','G','H','J','K','L','M','N','O','P','R','S','T','U','V','W','X','Y','Z'];
    var out='';
    for(var i=0;i<len;i++){
        var ch=Math.random(1,2);
        if(ch<0.5){
           var ch2=Math.ceil(Math.random(1,ints.length)*10);
           out+=ints[ch2];
        }else{
           var ch2=Math.ceil(Math.random(1,chars.length)*10);
           out+=chars[ch2];            
        }
    }
    document.getElementById("generatecode").innerHTML = out;
}
generate(9);
<span id="generatecode"></span>

I don’t know what to do, that’s why I’m posting here

2

Answers


  1. Couple of things to note here:

    • You’re defining generate with args (len, type), but you call it as generate(9); Why?
    • Math.random(); takes no arguments; it simply returns a value between 0 and 1, but it never returns 1. You can instead use Math.floor(Math.random() * maxNumber) where maxNumber is the maximum number. It’ll return 0 to maxNumber-1. (if you want, make it Math.floor(Math.random() * maxNumber) + 1 to make it 1 to maxNumber).
    • Arrays are zero indexed; meaning they start at 0. <array>.length returns the amount of elements are there in the array, but to get the last element you must use <array>[<array>.length-1].
    Login or Signup to reply.
  2. Math.random doesn’t take any arguments.

    If you want a random value in range use:

    function random(min, max) {
      return Math.random() * (max - min) + min
    }
    
    function generate(len, type) {
      var ints = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
      var chars = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
      var out = '';
      for (var i = 0; i < len; i++) {
        var ch = Math.random();
        if (ch < 0.5) {
          var ch2 = Math.floor(random(0, ints.length));
          out += ints[ch2];
        } else {
          var ch2 = Math.floor(random(0, chars.length));
          out += chars[ch2];
        }
      }
      document.getElementById("generatecode").innerHTML = out;
    }
    generate(9);
    
    function random(min, max) {
      return Math.random() * (max - min) + min
    }
    <span id="generatecode"></span>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search