Say you have the following array:
let characters = ['ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'abcdefghijklmnopqrstuvwxyz', '1234567890', '!@#$%^&*()'];
Would it be possible to get a random string, from any index? Say I wanted at least 1 string value from index 0. Could I loop through the array, and grab the random letter from index 0? What would that look like?
You can create a random index with Math.floor(Math.random()*str.length)
Math.random creates a random number between 0(inclusive) and 1(exclusive), multiplying by str.length, in your example 26, gives a random number between 0(inclusive) and 26(exlusive). Math.floor then rounds that number down to the closest integer. so you’ll get a random integer between 0(inclusive) and 25(inclusive).
I assume this is the main part you are having problems with?
That’s exactly what is the problem. So far I have:
Math.floor(Math.Random() * characters[0].toString().length);
But all that does is return numbers.
Yeah, math.floor returns a number. You now need to use that number to retrieve a character from the characters[0] string. Also, it’s already a string, so you don’t need to call toString()
let index = Math.floor(Math.random() * characters[0].length);
let randomCapitalLetter = characters[0][index];
Did you get a TypeError for that?
fixed it, I accidentally capitalised random
I didn’t see that finer detail, sorry. But thank you for your help!
1 Like
mind posting the answere for other people?
let characters = ['ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'abcdefghijklmnopqrstuvwxyz', '1234567890', '!@#$%^&*()'];
const getRandomCapital = () => characters[0][Math.floor(Math.random()*characters[0].length)]
//or
function getRandomCapital(){
let index = Math.floor(Math.random() * characters[0].length);
return (characters[0][index]);
}
1 Like