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

Javascript 如何使多个if语句更简洁?,javascript,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.backg

我试图使这个脚本更简洁,因为我将在将来添加更多的语句

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

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

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

如果不需要用于其他目的的随机值,则可以获取数组并检查是否获得用于设置颜色的值

var x=['red','blue','yellow'][Math.floor(Math.random()*9)],
一=document.getElementById(“测试”);
如果(x)one.style.backgroundColor=x

测试
另一个解决方案可能是在
ID
颜色
之间创建一个。注意:这允许为
非连续的
索引定义值。此外,例如,您可以将多个映射指定给某个颜色,以使它们具有更大的概率

让bgColor=newmap();
bgColor.set(1,{bg:“红色”,c:“黑色”});
bgColor.set(2,{bg:“蓝色”,c:“白色”});
bgColor.set(3,{bg:“绿色”,c:“红色”});
bgColor.set(4,{bg:“天蓝色”,c:“黑色”});
bgColor.set(5,{bg:“褐红色”,c:“白色”});
bgColor.set(6,{bg:“红色”,c:“黑色”});
bgColor.set(7,{bg:“红色”,c:“黑色”});
bgColor.set(8,{bg:“蓝紫色”,c:“白色”});
var one=document.getElementById(“测试”);
setInterval(函数()
{
设x=Math.floor((Math.random()*9)+1);
设{bg,c}=bgColor.get(x)|{;
控制台日志(x,bg,c);
如果(背景)
{
1.style.backgroundColor=bg;
1.style.color=c;
}
}, 1000);

我会像锡安的狮子一样铁石心肠
另一种可能性,如果你的最终目标是在一系列相等权重的值之间随机选择,那么你可以编写一个简单的函数来接受这些值,然后返回一个或返回一个函数,调用时返回一个。这是第二个版本:

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

document.body.style.backgroundColor=randomColor()
另一种方法是实现一个简单的称重系统

const colors=[
{颜色:'天蓝色',重量:1},
{颜色:橙色,重量:2},
{颜色:'黑色',重量:1},
{颜色:'teal',重量:3}
].reduce((res,{color,weight})=>[…res,…数组(weight).fill(color)],[]);
const randomColor=()=>colors[Math.floor(colors.length*Math.random());
//演示
数组(50).fill().forEach(()=>{
const el=document.createElement('div');
常量颜色=随机颜色();
el.innerText=颜色;
el.style.backgroundColor=颜色;
文件.正文.附件(el);

});如果你的代码有效,并且你寻求建设性的批评或改进,你应该继续询问。@Amy同意。然而,事实是,“规则”被选择性地或完全地忽略了;(因此,可以根据用户的个人判断完全或有选择地忽略,而不会与“规则”的实际实践发生冲突或行为不一致。)@guest271314您的观点是什么?总会有人无视规则。这不是你也可以无视他们的理由。@Amy同意你的看法。你是对的。
新地图([“红色”、“蓝色”、“绿色”、“天蓝色”、“栗色”)。地图((a,i)=>[i+1,a])
@guest271314这是一个很好的
单行初始化!这很好。我想加权比这更难。您也可以从
{skyblue:1,organgered:2,black:1,teal:3}
开始,这可能更容易维护。@ScottSauyet true。然而,这种方式允许相同颜色的多个条目,这在某些情况下可能是可取的。但是,是的,这只是一个微小的区别。