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
Couple of things to note here:
generate
with args(len, type)
, but you call it asgenerate(9);
Why?Math.random();
takes no arguments; it simply returns a value between 0 and 1, but it never returns 1. You can instead useMath.floor(Math.random() * maxNumber)
wheremaxNumber
is the maximum number. It’ll return 0 to maxNumber-1. (if you want, make itMath.floor(Math.random() * maxNumber) + 1
to make it 1 to maxNumber).<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]
.Math.random
doesn’t take any arguments.If you want a random value in range use: