在项目开发过程中会运用到很多的if-else或者switch,项目会变得臃肿以及难以阅读,试着去优化它们
假设后端传给我们一个类型,我们需要根据类型返回他真实的含义,用if-else会是这样
function getTranslation(type) {
if (type === 1) {
return "smokeId";
} else if (type === 2) {
return "engineId";
} else if (type === 3) {
return "cluserId";
} else if (type === 4) {
return "wahaha";
}
return "all in";
}
这并不是很好 然后通过switch去优化它
function getTranslation(type) {
switch (type) {
case 1:
return "smokeId";
case 2:
return "engineId";
case 3:
return "cluserId";
case 4:
return "wahaha";
default:
return "all in";
}
}
switch虽然看起来比if-else好点,但是也容易出错,目前可能最佳的方案是用双问号 ??
function getTranslation(type) {
const types = {
1: 'smokeId',
2: 'engineId',
3: 'cluserId',
4: 'wahaha'
}
return types[type] ?? 'all in'
}
我们创了一个对象,其中键是条件,值是响应。然后我们可以使用方括号符号从传入的参数中选择对象的正确值。 函数return types[type] ?? 'all in' 使用无效合并来分配默认相应,意味着如果types[type]为null或者undefined(且不是0或者fasle),则返回默认字符串'all in'
上述只是很偏的用法 真的用到的地方比如 value1 ?? value2 value3 || value4
这个在很多情况下 比 || 更好用 因为 ?? 是只有value1是undefind或者null的时候才会是value2,在传值给后端的时候比较好用,说白了 也就是更加适合在不知道变量是否有值时使用。
toFixed问题
在开发过程种需要保留小数点后两位 由于后端给的是未经过百分比,例如0.0023568,需要处理 当我先用Number转数字后用toFixed时,小数点后出现了很多位例如70.111111111111111%这样的情况,这是由于toFixed()返回的str类型