const howLong = 5
let special = [
"!",
"@",
"#",
"$",
"%",
"+",
"&",];
let finalPassword = []
for (let i = 0; i < howLong; i++) {
finalPassword += special[Math.floor(Math.random() * howLong)].push
}
console prints undefined 5x, my goal is to make it copy 5 random characters from the "special" array into a new var "finalPassword"
you should remove the .push call
const howLong = 5;
let special = [
"!",
"@",
"#",
"$",
"%",
"+",
"&",];
let finalPassword = "";
for (let i = 0; i < howLong; i++) {
finalPassword += special[Math.floor(Math.random() * howLong)]
}
Depending on what your expected output requirements are you can either concatenate "special" characters on to a string:
const howLong = 5;
let special=["!","@","#","$","%","+","&"];
let finalPassword = '';
for (let i = 0; i < howLong; i++) {
const rnd = Math.floor(Math.random() * howLong);
finalPassword += special[rnd];
}
console.log(finalPassword);
...or you can push those "special" characters into an array (and then maybe join up that array of elements into a string).
const howLong = 5;
let special=["!","@","#","$","%","+","&"];
let finalPassword = [];
for (let i = 0; i < howLong; i++) {
const rnd = Math.floor(Math.random() * howLong);
finalPassword.push(special[rnd]);
}
console.log(finalPassword);
console.log(finalPassword.join(''));
But you can't do both operations at the same time.
In the for loop iteration, generate a random index and then access the special array in that index to fetch the special character.
const howLong = 5;
let special = [
"!",
"@",
"#",
"$",
"%",
"+",
"&",];
let finalPassword = []
for (let i = 0; i < howLong; i++) {
const currentRandom = Math.floor(Math.random() * howLong);
finalPassword.push(special[currentRandom]);
}
console.log(finalPassword);