如何使多个if语句更简洁?

时间:2019-02-12 21:13:18

标签: javascript

我正在尝试使此脚本更简洁,因为将来我将添加更多的语句。

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";
}

5 个答案:

答案 0 :(得分:6)

您可以将属性和值存储在一个普通对象中

const o = {1:'a',2:'b',3:'c'}
one.style.backgroundColor = o[x]

答案 1 :(得分:1)

如果您不需要将随机值用于其他目的,则可以获取一个数组并检查是否有truthy值用于设置颜色。

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>

答案 2 :(得分:1)

另一个解决方案可能是在idscolors之间创建一个Map。请注意,这样可以为non-consecutive索引定义值。另外,例如,您可以将多个映射分配给某种颜色,以赋予它们更大的可能性。

let bgColor = new Map();
bgColor.set(1, {bg:"red", c:"black"});
bgColor.set(2, {bg:"blue", c:"white"});
bgColor.set(3, {bg:"green", c:"red"});
bgColor.set(4, {bg:"skyblue", c:"black"});
bgColor.set(5, {bg:"maroon", c:"white"});
bgColor.set(6, {bg:"red",c:"black"});
bgColor.set(7, {bg:"red",c:"black"});
bgColor.set(8, {bg:"BlueViolet", c:"white"});

var one = document.getElementById("test");

setInterval(function()
{
    let x = Math.floor((Math.random() * 9) + 1);
    let {bg, c} = bgColor.get(x) || {};        
    console.log(x, bg, c);

    if (bg)
    {
        one.style.backgroundColor = bg;
        one.style.color = c;
    }
}, 1000);
<div id="test">I'm Gonna be Iron Like a Lion in Zion</div>

答案 3 :(得分:0)

另一种可能性是,如果您的最终目标是简单地在多个相等权重的值之间随机选择,则可以编写一个接受这些值的简单函数,然后返回一个或返回一个函数,该函数在调用时返回一个。这是第二个版本:

const randomChoice = (vals) => () => vals[Math.floor(vals.length * Math.random())]
const randomColor = randomChoice(['red', 'blue', 'yellow'])

document.body.style.backgroundColor = randomColor()

randomChoice是一个实用函数,可能存储在其他位置,randomColor生成您需要的项目之一。

这可能无法满足您的需求。但是,如果三个分支只是占位符,并且您最终需要代码建议的九个分支,那么这可能是最容易更新的。

可以将其扩展为处理不等的权重,但是会更加复杂。在很多地方,这种随机选择可能会有用。

答案 4 :(得分:0)

另一种实现方法是实现简单的体重系统。

const colors = [
  { color: 'skyblue', weight: 1 },
  { color: 'orangered', weight: 2 },
  { color: 'black', weight: 1 },
  { color: 'teal', weight: 3 }
].reduce((res, {color, weight}) => [...res, ...Array(weight).fill(color)],[]);

const randomColor = () => colors[Math.floor(colors.length * Math.random())];


// Demo
Array(50).fill().forEach(() => {
  const el = document.createElement('div');
  const color = randomColor();
  el.innerText = color;
  el.style.backgroundColor = color;
  document.body.append(el);
});

相关问题