优化下面的代码,使其更加简洁if(name.indexOf("风机") != -1){ return "fan"; }else if(name.indexOf("补光灯") != -1){ return "lamp"; } else if (name.indexOf("天窗") != -1) { return "window"; } else if (name.indexOf("卷帘") != -1) { return "shutter"; } else if (name.indexOf("水肥机") != -1) { return "machine"; } else if (name.indexOf("水阀") != -1) { return "valve"; } else if (name.indexOf("湿帘") != -1) { return "curtain"; } else if (name.indexOf("卷被") != -1) { return "quilt"; }
时间: 2024-02-14 21:06:15 浏览: 114
可以使用 switch/case 语句来简化代码,如下所示:
```
switch(name) {
case "风机":
return "fan";
case "补光灯":
return "lamp";
case "天窗":
return "window";
case "卷帘":
return "shutter";
case "水肥机":
return "machine";
case "水阀":
return "valve";
case "湿帘":
return "curtain";
case "卷被":
return "quilt";
default:
return "";
}
```
这样可以将多个 if/else if 语句简化为一个 switch/case 语句,使代码更加简洁易读。
阅读全文