0

I want get random HEX color. that is my code (JavaScript):

 let colors = ['1','2','3','4','5','6','7','8','9','0','A','B','C','D','E','F']; 
 let random = colors[Math.floor(Math.random() * colors.length)];
 
 console.log(`#${random}${random}${random}${random}${random}${random}`);

but it returns the same element whenever I call a variable (for exam. "#cccccc", "#999999"..).

Do I have to set the variable 6 times, or there is a shorter way?

any feedback will help me.(I am an absolute beginner with programming)

Chani f
  • 53
  • 6

4 Answers4

0

You can use a for loop to iterate, try this:

let colors = ['1','2','3','4','5','6','7','8','9','0','A','B','C','D','E','F']; 
let digits = 10;
let result = "#";

for(i = 0; i < digits; i++){
    result += colors[Math.floor(Math.random() * colors.length)]
}
console.log(result);
sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35
0

Right now your code is making the variable random, but never changing it. So, when you log it, it uses the same letter or number over and over again. Below is a solution.

function randomHex() {
  let colors = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'A', 'B', 'C', 'D', 'E', 'F'];
  let hex = "#";
  for (let i = 0; i < 6; i++) {
    hex += colors[Math.floor(Math.random() * colors.length)];
  }
  return hex;
}
console.log(randomHex())
0

See this line:

let random = colors[Math.floor(Math.random() * colors.length)];

You might think that you are stating: "This is how I want a random value".

That's not how it's happening. You are fetching a random color once, and then assigning it to the variable random.

If you want it to be a generation rule, you would have to make random a function, not a variable:

function random() {
    return colors[Math.floor(Math.random() * colors.length)];
}

 console.log(`#${random()}${random()}${random()}${random()}${random()}${random()}`);
Andrew Shepherd
  • 44,254
  • 30
  • 139
  • 205
0

random is initialised (assigned a value) once. To continually re-initialise random, you could use a for loop. The block ({}) of a for loop is re-initialised each time you iterate (go through) the loop. For example:

function randomHex() {

let colors = ['1','2','3','4','5','6','7','8','9','0','A','B','C','D','E','F']; 

symbolArray = []

for (let counter = 0; counter < 6; counter++) {
    let randomSymbol = colors[Math.floor(Math.random() * colors.length)];
    symbolArray.push(randomSymbol)
}

let hexNumbers = symbolArray.join('');

console.log('#' + hexNumbers);
}

randomHex();
randomHex();
randomHex();
tonitone120
  • 1,920
  • 3
  • 8
  • 25