// 案例: function previewWeek(i) { switch (i) { case 1: return '星期一' break; case 2: return '星期二' break; case 3: return '星期三' break; case 4: return '星期四' break; case 5: return '星期五' break; case 6: return '星期六' break; case 7: return '星期日' break; default: return '' } } // 优化: function previewWeeks(i) { return i > 0 && i < 8 ? `星期${['一', '二', '三', '四', '五', '六', '日'][i - 1]}` : '错误' } console.log(previewWeeks(5))
// 案例: function verifyIdentity(identityId) { if (identityId == 1 || identityId == 2 || identityId == 3 || identityId == 4) { return '你的身份合法,请通行!' } else { return '你的身份未知,警告!' } } // 优化: function verifyIdentitys(identityId) { return [1, 2, 3, 4].includes(identityId) ? '你的身份合法,请通行!' : '你的身份未知,警告!' } console.log(verifyIdentitys(3))
// 案例: function fn() { console.log(123) } function fn2(a) { return a > 5 } if (fn2(6)) { fn() } // 优化: function yh() { console.log(123) } function yh2(a) { return a > 5 } yh2(6) && fn()
// 案例: function getPosition(direction) { if (direction == "left") { return "左" } else if (direction == "right") { return "右" } else if (direction == "top") { return "上" } else if (direction == "bottom") { return "下" } else { return "未知" } } console.log(getPosition('left')) // 优化: function getPositions(direction) { return ({ left: '左', right: '右', top: '上', bottom: '下' })[direction] || '' } console.log(getPositions('left'))