skip to Main Content

I want to repeat the for loop which get us new values every time.
Whenever I will run the for loop I should get the values different.
Please solve my problem

let hex = 'ABCDEF0123456789';
let res = '';
for (let i = 1; i <= 6; i++) {
    res += hex.charAt(Math.floor(Math.random() * hex.length));
    // console.log(i);
} 

I want to get new values every time when I call or run the for loop.
For Example – If I print the value of res multiple times. Every time
I want the value different

2

Answers


  1. Did you mean that you want to put your code in a function an call the function?

    function res() {
      let hex = 'ABCDEF0123456789';
      let res = '';
      for (let i = 1; i <= 6; i++) {
        res += hex.charAt(Math.floor(Math.random() * hex.length));
      }
      return res;
    }
    
    console.log(res()) // => one value
    console.log(res()) // => another value
    console.log(res()) // => a third value
    
    Login or Signup to reply.
  2. let hex = 'ABCDEF0123456789';
    let res = '';
    for (let i = 1; i <= 6; i++) {
      res = hex[Math.floor(Math.random() * hex.length)];
      console.log(res);
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search