Home > Back-end >  Why getting undefined while concating string in javascript?
Why getting undefined while concating string in javascript?

Time:10-01

I have an empty string named newPassword and an array named passwordList. I am taking an item from the passwordList array and Concating it to the string newPassword. When I am printing the newPassword to the console it is showing undefined for some array items.

I have converted the number from 33 to 126 to it equivalent ASCII character and stored it in the array passwordList.

Here is my code:

import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { newPass } from '../redux/slice';

const ItemMixer = () => {
  let {passwordLength, password} = useSelector(
    state => state.passwordLength,
  );
  const dispatch = useDispatch();

  // converting number to equivalent ascii character
  const passwordList = [];
  for (let index = 33; index <= 126; index  ) {
    passwordList[index - 33] = String.fromCharCode(index);
  }

  let newPassword = '';
  const generatePassword = () => {
    newPassword = '';
    let loop = passwordLength;
    while (loop--) {
      let randomNumber = Math.floor(Math.random() * 126);
      if (randomNumber < 33) {
        randomNumber  = 33;
      }
      console.log(randomNumber, passwordList[randomNumber]);
      newPassword  = passwordList[randomNumber];
    }
    dispatch(newPass(newPassword))
  };

  return (
    <div>
      <button
        className="btn btn-primary"
        onClick={() => generatePassword()}>
        Generate
      </button>
      <h3>Password: {password}</h3>
    </div>
  );
};

export default ItemMixer;

I am getting output like this:

45 'N'
100 undefined
37 'F'
123 undefined
72 'i'
112 undefined
50 'S'
46 'O'

Why I am getting undefined? How can I fix the problem?

CodePudding user response:

You should multiple the Math.random() by 93 to get the random index because this is the number of items in passwordList ( 126 - 33 )

// converting number to equivalent ascii character
  const passwordList = [];
  for (let index = 33; index <= 126; index  ) {
    passwordList[index - 33] = String.fromCharCode(index);
  }

  let newPassword = '';
  const generatePassword = () => {
    newPassword = '';
    let loop = 5;
    while (loop--) {
      let randomNumber = Math.floor(Math.random() * 93);
      console.log(randomNumber, passwordList[randomNumber]);
      newPassword  = passwordList[randomNumber];
    }
  };
  generatePassword()

  • Related