1. 常用条件判断
1.1 逻辑运算符
使用JavaScript逻辑运算符进行判断。
1 === 1 // true | 相等1!== 1 // false | 不等1 < 1 // false | 小于1 > 1 // false | 大于1 <= 1 // true | 小于或等于1 >= 1 // true | 大于或等于1 == 1 && 1 == 2 // false | 与运算、两边的条件符合成立1 == 1 || 1 == 2 // true | 或运算、一边条件符合即成立
1.2 if 语句
if 条件语句的几种形态。
// ifif (true) {// 执行}// if elseif (1>2) {} else {// 执行}// else ifif (1>2) {} else if (1<2) {// 执行} else {}
1.3 switch 语句
if 之外的另一种条件判断语句。
var n = 1switch(n) {case 1:// n = 1 执行break;case 2:// n = 2 执行break;default:// n 既不等于 1 也不等于 2 执行}
2.优化逻辑判断
2.1 嵌套层级优化
下面的条件判断,存在三层 if 条件嵌套
function supply(fruit, quantity) {const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];// 条件 1: 水果存在if (fruit) {// 条件 2: 属于红色水果if (redFruits.includes(fruit)) {console.log('红色水果');// 条件 3: 水果数量大于 10 个if (quantity > 10) {console.log('数量大于 10 个');}}} else {throw new Error('没有水果啦!');}}
提前return无效条件
如果提前 return 掉无效条件,将 if else 的多重嵌套层次减少到一层,更容易理解和维护
function supply(fruit, quantity) {const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];if (!fruit) throw new Error('没有水果啦'); // 条件 1: 当 fruit 无效时,提前处理错误if (!redFruits.includes(fruit)) return; // 条件 2: 当不是红色水果时,提前 returnconsole.log('红色水果');// 条件 3: 水果数量大于 10 个if (quantity > 10) {console.log('数量大于 10 个');}}
2.2 多条件分支的优化处理
当需要枚举值处理不同的业务分支逻辑时,第一反应是写下 if else ?我们来看一下:
function pick(color) {// 根据颜色选择水果if (color === 'red') {return ['apple', 'strawberry'];} else if (color === 'yellow') {return ['banana', 'pineapple'];} else if (color === 'purple') {return ['grape', 'plum'];} else {return [];}}
在上面的实现中:
- if else 分支太多
- if else 更适合于条件区间判断,而 switch case 更适合于具体枚举值的分支判断
改用switch case
function pick(color) {// 根据颜色选择水果switch (color) {case 'red':return ['apple', 'strawberry'];case 'yellow':return ['banana', 'pineapple'];case 'purple':return ['grape', 'plum'];default:return [];}}
switch case 优化之后的代码看上去格式整齐,思路很清晰,但还是很冗长。继续优化:
Object{ key: value } 结构优化
借助 Object 的 { key: value } 结构,我们可以在 Object 中枚举所有的情况,然后将 key 作为索引,直接通过 Object.key 或者 Object[key] 来获取内容。
const fruitColor = {red: ['apple', 'strawberry'],yellow: ['banana', 'pineapple'],purple: ['grape', 'plum'],}function pick(color) {return fruitColor[color] || [];}
const condition = 2let obj = {'1' : () => { document.write(1) },'2' : () => { document.write(2) },'3' : () => { document.write(3) },}obj[condition]()
使用 Map 数据结构,真正的 (key, value) 键值对结构
const fruitColor = new Map().set('red', ['apple', 'strawberry']).set('yellow', ['banana', 'pineapple']).set('purple', ['grape', 'plum']);function pick(color) {return fruitColor.get(color) || [];}
优化之后,代码更简洁、更容易扩展。
使用 Array.filter 达到同样的效果
为了更好的可读性,还可以通过更加语义化的方式定义对象,然后使用 Array.filter 达到同样的效果。
const fruits = [{ name: 'apple', color: 'red' },{ name: 'strawberry', color: 'red' },{ name: 'banana', color: 'yellow' },{ name: 'pineapple', color: 'yellow' },{ name: 'grape', color: 'purple' },{ name: 'plum', color: 'purple' }];function pick(color) {return fruits.filter(f => f.color == color);}
2.3 多条件分支判断
编码时遇到多个判断条件时,本能的写下下面的代码(其实也是最能表达业务逻辑的面向过程编码)。
function judge(fruit) {if (fruit === 'apple' || fruit === 'strawberry' || fruit === 'cherry' || fruit === 'cranberries') {console.log('red');}}
但是当 type 未来到 10 种甚至更多时, 我们只能继续添加 || 来维护代码么?
Array.includes
// 将判断条件抽取成一个数组const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries'];function judge(type) {if (redFruits.includes(fruit)) {console.log('red');}}
2.4 判断数组中是否所有项都满足某条件
🙌🌰
const fruits = [{ name: 'apple', color: 'red' },{ name: 'banana', color: 'yellow' },{ name: 'grape', color: 'purple' }];function match() {let isAllRed = true;// 判断条件:所有的水果都必须是红色for (let f of fruits) {if (!isAllRed) break;isAllRed = (f.color === 'red');}console.log(isAllRed); // false}
上面的实现中,主要是为了处理数组中的所有项都符合条件。
Array.every
使用 Array.every 可以很容的实现这个逻辑:
🙌🌰
onst fruits = [{ name: 'apple', color: 'red' },{ name: 'banana', color: 'yellow' },{ name: 'grape', color: 'purple' }];function match() {// 条件:所有水果都必须是红色const isAllRed = fruits.every(f => f.color == 'red');console.log(isAllRed); // false}
2.5 判断数组中是否存在某项满足条件
Array.some
相同的方式,如果我们想测试是否存在红色的水果,我们可以使用 Array.some 一行代码实现。
🙌 🌰
const fruits = [{ name: 'apple', color: 'red' },{ name: 'banana', color: 'yellow' },{ name: 'grape', color: 'purple' }];function test() {// 条件:任何一个水果是红色const isAnyRed = fruits.some(f => f.color == 'red');console.log(isAnyRed); // true}
2.6 && 运算符 仅在为 true 的情况下
如果仅在变量值为 true 的情况下才调用函数,则可以使用 && 运算符。
🙌🌰
// 长if (test1) {callMethod();}// 短test1 && callMethod();
