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"
CodePudding user response:
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)]
}
CodePudding user response:
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.
CodePudding user response:
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);
CodePudding user response:
In your example you simply have to remove .push
it seems.
let special = ["!", "@", "#", "$", "%", " ", "&"];
let finalPassword = [];
for (let i = 0; i < 5; i ) {
finalPassword = special[Math.floor(Math.random() * 5)];
}
console.log({ finalPassword });