Reputation: 147
I have this javascript code:
var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
key = '',
c;
for (i = 0; i < 32; i++) {
c = Math.floor(Math.random() * chars.length + 1);
key += chars.charAt(c)
}
console.log('return key length that needs to be 32...' + key.length);
I need to always return 32 key length..but i get random:
return key length that needs to be 32...31
return key length that needs to be 32...29
return key length that needs to be 32...32
return key length that needs to be 32...31
return key length that needs to be 32...30
return key length that needs to be 32...32
return key length that needs to be 32...31
I know that error is in: i<32;
but javascript freezes when i add i=32;
i try i<=32
but same results...so i know it is basic question but i don't know hot to return always 32 key length?
Upvotes: 0
Views: 57
Reputation: 23
Sometimes math.random() return such value (Math.random() * chars.length + 1) becomes >= 64.
Math.random()*char.length+1 >= 64
Math.random()*char.length >= 63
Math.random()* >= 63/64 (in our case)
Math.random() >= 0.984375
If math.random returns value >= 0.984375 then c will be get 64 so length of key will be less than 32. You don't need to add 1 to solve this problem.
Upvotes: 1
Reputation: 13060
The problem is here Math.floor(Math.random() * chars.length + 1);
Math.random()
returns a number between 0 and 1, inclusive. When it's 1 then Math.floor(1 * 32 + 1)
gives 33
chars.charAt(33)
is undefined
though and results in nothing being added to key
hence the random lengths.
Remove the + 1
and it should work as you expected.
Upvotes: 2
Reputation: 174
Try this
var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
key = '',
c;
for (i=0;i<32;i++) {
c = Math.floor(Math.random()*chars.length);
key += chars.charAt(c);
}
console.log('return key length that needs to be 32...'+key.length);
Upvotes: 1
Reputation: 780808
The problem is the + 1
in this line:
c = Math.floor(Math.random() * chars.length + 1);
Valid indexes run from 0
to chars.length-1
. The above assignment picks a random number from 1
to chars.length
. So it ignores the first character in the string, and sometimes tries to access outside the string. In the latter case it chars.charAt(c)
returns undefined
, and appending that doesn't add to the length of the result.
var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
key = '',
c;
for (i = 0; i < 32; i++) {
c = Math.floor(Math.random() * chars.length);
key += chars.charAt(c)
}
console.log('return key length that needs to be 32...' + key.length);
Upvotes: 4