+ 2
To pick a random letter from a list: const letters = "abcde.."; const randomLetter = letters[Math.floor(Math.random() * letters.length)]; console.log(randomLetter); `Math.random()` gives you a random number between 0 and 1. Multiplying that by `letters.length` will give you a random number between 0 and however many letters there are. `Math.floor` will round it down to the nearest whole number. That number you can then use to index into the list, using square brackets. Hope that helps. To generate a password, simply do that 8 times, and add it all up.
13th Mar 2022, 12:13 AM
Schindlabua
Schindlabua - avatar
+ 2
Well I don't just want to spell it all out, that's no way to learn :p Look at my first comment, then my latest. Put the two together..
13th Mar 2022, 12:50 AM
Schindlabua
Schindlabua - avatar
+ 1
Use Math.round() instead of Math.floor()(it drops the floor to integer) Because Math.round() will round it to nearest whole number(it can increment or decrement some value from it to make it a whole number) While Math.floor() will just drop the value after points(it will always decrement a value to make a whole number) By using Math.floor chances will be very low of getting the word z As Math.floor(25.9999999) = 25 Math.round(25.6) = 26
13th Mar 2022, 12:38 AM
Umar Farooq
+ 1
Oh thats why. Btw ty for correction
13th Mar 2022, 12:44 AM
Umar Farooq
0
UMAR FAROOQ That will lead to errors! If you have a list of size 26, and want to pick a random element from it, you need to generate a random number between 0 and 25. letters[25] == "z" So Math.floor is absolutely correct in this case.
13th Mar 2022, 12:42 AM
Schindlabua
Schindlabua - avatar
0
Your Mom sure. let password = ""; // fill that up in the loop const length = 8; for(let i = 0; i < length; i++) { // generate a random letter here, then password += randomLetter; } // finished password is now in variable `password`
13th Mar 2022, 12:46 AM
Schindlabua
Schindlabua - avatar
0
Same thing you did but using document.write 😎
14th Mar 2022, 7:26 AM
Ahmed Waiz
Ahmed Waiz - avatar
- 1
Use document.write
13th Mar 2022, 3:22 PM
Ahmed Waiz
Ahmed Waiz - avatar
- 1
cause and effect: You see 01234567 in your output. What line could be causing it? Try removing lines of code until the 01234567 disappers. Then think about what would need to happen to make some different output appear. I've given you the keys to the kingdom, you just need to copy and paste the two pieces of code I've given you, no extra coding required :p Also, you might want to review the javascript lessons on loops, and strings.
13th Mar 2022, 5:54 PM
Schindlabua
Schindlabua - avatar
14th Mar 2022, 7:23 AM
Ahmed Waiz
Ahmed Waiz - avatar