Home > Software design >  How to set color from js for loop
How to set color from js for loop

Time:08-20

I want to change the background color of each player's list box based on their individual rating.

I have this, but it's cumbersome and hard to maintain:

rate_100 = getColor(); rate_200 = getColor(); rate_300 = getColor(); rate_400 = getColor();

First create the random colors: in this format: rate_100 rate_200 rate_300 etc.

function getColor(){ 
return `hsla(${~~(360 * Math.random())},70%,30%,0.13)`;
}

function classColor() { 
walk = 0;
for (i=0; i<=25; i  )   {
walk = walk   100;
`"rate_${walk.toString()}"` = getColor(); // Doesn't work
`rate_${walk} = getColor(); // and neither does this
}

Sample JS

function colorize(rating) { 
if (rating >= "2600") { return rate_2600; }
if (rating >= "2500") { return rate_2500; }
if (rating >= "2400") { return rate_2400; }
if (rating >= "2300") { return rate_2300; }
}

Can anyone help with the proper syntax in classColor() ?

CodePudding user response:

You're not assigning your variables correctly. I'm not 100% sure what you're trying to achieve, but you can take the following as an example and adjust as needed:

function getColor(){ 
return `hsla(${~~(360 * Math.random())},70%,30%,0.13)`;
};

const ratings = {}
function classColor() { 
for (let walk = 0; walk<=3000; walk =100){
const rating = `rate_${walk.toString()}`;
ratings[rating]={color: getColor()};
}
};

classColor();
console.log(ratings);

  • Related