Click here to Skip to main content
15,937,012 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to generate a random password but it always prints the same number?!?

const characters = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9","~","`","!","@","#","$","%","^","&","*","(",")","_","-","+","=","{","[","}","]",",","|",":",";","<",">",".","?",
"/"];
let passElOne = document.getElementById("pass1");
let passElTwo = document.getElementById("pass2");

function generatePass()
{
   
        let randomChar = Math.floor(Math.random() * characters.length)
        let newChar = characters[randomChar]
       
    
        let randomPassword = ""
        for(i = 0; i < 15; i++)
        {
            randomPassword += newChar;
        }
        passElOne.textContent = randomPassword;
   
}


What I have tried:

I'm pretty limited on my javascript skills since I'm learning this language the only that I try is to write some if else conditions but it don't work
Posted
Updated 15-Jan-23 23:31pm

JavaScript
for(i = 0; i < 15; i++)
{
    randomPassword += newChar; // add the same character each time
}

You are adding 15 of the same character to your password. You need to generate a new random character each time round the loop:
JavaScript
for(i = 0; i < 15; i++)
{
    let randomIndex = Math.floor(Math.random() * characters.length)
    randomPassword += characters[randomIndex];
}
 
Share this answer
 
Comments
oceanotrash 14-Jan-23 11:27am    
it works! thank you i really forgot that characters[array]
Or you can use crypto lib built into browser

JavaScript
function bytestohex(bytes) {
    var hexstring='', h;
    for(var i=0; i<bytes.length; i++) {
        h=bytes[i].toString(16);
        if(h.length==1) { h='0'+h; }
        hexstring+=h;
    }   
    return hexstring;
}

bytestohex(window.crypto.getRandomValues(new Uint8Array(15)));
 
Share this answer
 
Comments
Richard Deeming 16-Jan-23 5:22am    
👍 Pretty good browser support too:
Crypto.getRandomValues() - Web APIs | MDN[^]
Lets see if you can figure out this one :)

JavaScript
[...Array(40)].map(e=>~~(Math.random()*40))
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900