在JavaScript中可以用来控制流程的语句通常有
当然还包括break,continue,try…catch等,不过今天重点讲的是如何优化if else语句
-
使用三元表达式
// old if (isSuccess) { success(); } else { rejected(); } // new isSuccess ? success() : rejected();
-
使用短路运算符
// old if (isSuccess) { success(); } // new isSuccess && success();
-
提前返回
function trafficLight(light) { if (light.color === 'red') return red(); if (light.color === 'green') return green(); yellow(); } // 如果只有一行代码直接return提前返回
-
使用switch case
// bad if (age === 10 || age === 20 || age === 30 || age === 40) { test(); } // good switch(age) { case 10: case 20: case 30: case 40: test(); }
-
利用include做判断
// bad if (age === 10 || age === 20 || age === 30 || age === 40) { test(); } // good const ages = [10, 20, 30, 40]; if (ages.include(age)) { test(); }
-
利用逻辑与运算符(||) 模拟Array.some方法
function assert(el, top, left, width) { let oldAxes = axes(el.left, el.top, el.width); let newAxees = axes(left, top, width); let compareTop = newAxees.unLeft[1] < oldAxes.upLeft[1]; let compareRight = newAxees.upLeft[0] > oldAxes.unRight[0]; let compareBottom = newAxees.upLeft[1] > oldAxes.unLeft[1]; let compareLeft = newAxees.upRight[0] < oldAxes.unLeft[0]; // 上面4个方法均返回布尔值 只要有一个为真则断言为真 return compareTop || compareRight || compareBottom || compareLeft }
-
优雅的判断一个数字在某个区间(比如:0~360),分成8等份,分别是 0-45、46-90、91-135 等等依次类推。
// bad if (degree < 45) { } else if (degree < 90) { } else if (degree < 135) { // 一直到360 }
// good // 优雅的判断一个数在某个区间0~360分八份 const rangeMap = { A: function () { console.log("0-45"); }, B: function () { console.log("45-90"); }, C: function () { console.log("90-135"); }, // move... }; // 建立映射关系 const angleArray = ["A", "B", "C", "D", "E", "F", "G", "H"]; const range = [45, 90, 135, 180, 225, 270, 315, 360]; const getAngleMap = (num) => { for (let i = 0; i < range.length; i++) { if (num <= range[i]) { return angleArray[i]; } } }; // 函数调用 rangeMap[getAngleMap(65)](); // 45-90
所以HR大哥别试了,我的技术不需要if来判断,让我去面试一下吧。。。。。。。。。o(╥﹏╥)o