Home > Net >  Why is the textContent not being replaced but rather added to when function is clicked?
Why is the textContent not being replaced but rather added to when function is clicked?

Time:07-16

const passwordBoxLeft = document.getElementById('password-box--left');
const passwordBoxRight = document.getElementById('password-box--right');

let passwordLeft = [];
let passwordRight = [];
let passwordLength = 15;

function generatePassword() {
  for (let i = 0; i < passwordLength; i  ) {
    let leftPW = characters[Math.floor(Math.random() * characters.length)];
    let rightPW = characters[Math.floor(Math.random() * characters.length)];
    passwordLeft.push(leftPW);
    passwordRight.push(rightPW);
  };

  passwordBoxLeft.textContent = passwordLeft.join('');
  passwordBoxRight.textContent = passwordRight.join('');
};

I have a simple frontend password generator that takes a characters array and generates 15 random characters from said array, pushes this into container arrays and these arrays are then displayed as textContent on the DOM.

Everything works well but for some reason, I am not understanding how to replace the textContent divs with a new rendition of a random password. Instead, the function is acting as if I have placed a = for textContent so it keeps joining on another 15 random characters and so on everytime it is clicked, rather than showing just a new set of 15 random characters. This is obviously not the intended behaviour.

I can't seem to workout what I am doing wrong exactly.

CodePudding user response:

You are using .push() method which adds one or more elements to the end of Array. It will always return new length of the Array.


In your case - .push() is adding new generated array to previously modified array.


let passwordLeft = [];
let passwordRight = [];
let passwordLength = 15;
let characters = `abcdefghijklmnopqrstuvwxyz`;
function generatePassword() {
  for (let i = 0; i < passwordLength; i  ) {
    let leftPW = characters[Math.floor(Math.random() * characters.length)];
    let rightPW = characters[Math.floor(Math.random() * characters.length)];
    passwordLeft[i] = leftPW;
    passwordRight[i] = rightPW;
  };
console.log(passwordLeft.join(""));
console.log(passwordRight.join(""));

}
generatePassword();

  • Related