Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make multiple if statements more concise? [closed]

Tags:

javascript

I am trying to make this script more concise, since I will be adding on more statements in the future.

x = Math.floor((Math.random() * 9) + 1);
var one = document.getElementById("test");

if(x === 1) {
  one.style.backgroundColor = "red";
}
if(x === 2) {
  one.style.backgroundColor = "blue";
}
if(x === 3) {
  one.style.backgroundColor = "yellow";
}
like image 660
Bryson Noble Avatar asked Jan 26 '23 17:01

Bryson Noble


2 Answers

You can store the properties and values in a plain object

const o = {1:'a',2:'b',3:'c'}
one.style.backgroundColor = o[x]
like image 141
guest271314 Avatar answered Jan 29 '23 07:01

guest271314


If you do not need the random value for other purpose, you could take an array and check if you got a truthy value for setting the color.

var x = ['red', 'blue', 'yellow'][Math.floor(Math.random() * 9)],
    one = document.getElementById("test");

if (x) one.style.backgroundColor = x;
<div id="test">test</div>
like image 36
Nina Scholz Avatar answered Jan 29 '23 07:01

Nina Scholz