Reputation: 19
So I am trying to build a simple password generator via JavaScript and the function just won't return anything, it will return nothing(blank).
let chars = "abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ"
let randomPass = ""
let passLen = 16
function ranNum() {
for ( let i=0; i<passLen.length; i++){
let randomLetter = Math.floor(Math.random() * chars.length) + 1
randomPass += chars.charAt(randomLetter)
}
return randomPass
}
function genPass() {
document.getElementById("div1").textContent = ranNum()
}
<button onclick="genPass()">Generate</button>
<div id="div1"></div>
Upvotes: 1
Views: 72
Reputation: 1
It's because you have the length property on passLen and the variable value is an int.
for ( let i=0; i<passLen; i++){
let randomLetter = Math.floor(Math.random() * chars.length) + 1
randomPass += chars.charAt(randomLetter)
}
Upvotes: 0
Reputation: 4078
In your for loop, passLen is not an array, it's already a length. So you don't need passLen.length
only passLen
.
let chars = "abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ"
let randomPass = ""
let passLen = 16
function ranNum() {
for (let i = 0; i < passLen; i++) {
let randomLetter = Math.floor(Math.random() * chars.length) + 1
randomPass += chars.charAt(randomLetter)
console.log(randomPass)
}
return randomPass
}
function genPass() {
document.getElementById("div1").textContent = ranNum()
}
<button onclick="genPass()">Generate</button>
<div id="div1"></div>
Upvotes: 0
Reputation: 3001
Your for loop is not executing because you are asking for passLen.length, and passLen is an integer it wont have a length, and then the loop won't run. just change your line
for ( let i=0; i<passLen.length; i++){
to for ( let i=0; i<passLen; i++){
and it will run fine.
let chars = "abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ"
let randomPass = ""
let passLen = 16
function ranNum() {
console.log('generate');
for ( let i=0; i<passLen; i++){
let randomLetter = Math.floor(Math.random() * chars.length) + 1
randomPass += chars.charAt(randomLetter);
console.log(randomLetter);
}
return randomPass
}
function genPass() {
document.getElementById("div1").textContent = ranNum()
}
<div id="div1">test</div>
<button onclick="genPass()">Generate password</button>
Upvotes: 1