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

4
我试图使这个脚本更简洁,因为我将来会添加更多的语句。
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";
}

4
如果你的代码可以运行并且想要得到建设性的评论或改进意见,你应该在[codereview.se]上发帖求助。 - user47589
@Amy 同意。然而,事实是 SO 上的“规则”被有选择性地或完全忽略了将数组中的最后一项移到第一位递归获取所有子元素(因此,可以根据个人用户判断有选择性地完全忽略或类似地行事,而不会违反或与“规则”的实际实践不一致)。 - guest271314
1
@guest271314 你的观点是什么?总会有人无视规则,这并不是忽略它们的理由。 - user47589
@Amy 同意你的观点。你是正确的。 - guest271314
5个回答

6

你可以将属性和值存储在简单的对象中

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

1
如果您不需要随机值用于其他目的,可以使用数组并检查是否获得了真值以设置颜色。

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>


1

另一个解决方案可能是创建一个Map,将idscolors联系起来。请注意,这使得可以为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>


2
new Map(["red", "blue", "green", "skyblue", "maroon"].map((a,i)=>[i+1,a])) - guest271314
@guest271314,这是一个不错的“一行代码”初始化! - Shidersz

0
另一个可能性,如果你的最终目标只是在一些等权值中简单地随机选择一个数的话,就可以编写一个简单的函数来接受这些值,然后返回其中一个或者返回一个函数,当调用时返回其中一个。以下是第二个版本:

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

document.body.style.backgroundColor = randomColor()

这里的randomChoice是一个实用函数,可能存储在其他地方,而randomColor生成你需要的其中一项。

这可能不符合您的需求。但如果这三个分支只是占位符,并且您最终需要代码建议的九个分支,则这可能是最容易保持最新的方法。

这可以扩展到处理不平等的权重,但会更加复杂。有很多地方可以使用这种随机选择。


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


这很好。我原以为加权会比这更困难。你也可以从 {skyblue: 1, organgered: 2, black: 1, teal: 3} 开始,这可能更容易维护。 - Scott Sauyet
@ScottSauyet 是的。然而,这种方式允许多次输入相同的颜色,在某些情况下可能是可取的。但是没错,这只是一个小差别。 - Olian04

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接