在任何编程语言中,代码需要根据不同的条件在给定的输入中做不同的决定和执行相应的动作。
例如,在一个游戏中,如果玩家生命点为0,游戏结束。在天气应用中,如果在早上被查看,显示一个日出图片,如果是晚上,则显示星星和月亮。在这篇文章中,我们将探索JavaScript中所谓的条件语句如何工作。
如果你使用JavaScript工作,你将写很多包含条件调用的代码。条件调用可能初学很简单,但是还有比写一对对if/else更多的东西。这里有些编写更好更清晰的条件代码的有用提示。
-
数组方法 Array.includes
-
提前退出 / 提前返回
-
用对象字面量或Map替代Switch语句
-
默认参数和解构
-
用 Array.every & Array.some 匹配全部/部分内容
-
使用可选链和空值合并
1. 数组方法 Array.includes
使用 Array.includes 进行多条件选择
例如:
1function printAnimals(animal) { 2 if (animal === 'dog' || animal === 'cat') { 3 console.log(I have a ${animal}); 4 } 5} 6 7console.log(printAnimals('dog')); // I have a dog 8
上面的代码看起来很好因为我们只检查了两个动物。然而,我们不确定用户输入。如果我们要检查任何其他动物呢?如果我们通过添加更多“或”语句来扩展,代码将变得难以维护和不清晰。
解决方案:
我们可以通过使用 Array.includes 来重写上面的条件
1function printAnimals(animal) { 2 const animals = ['dog', 'cat', 'hamster', 'turtle']; 3 4 if (animals.includes(animal)) { 5 console.log(I have a ${animal}); 6 } 7} 8 9console.log(printAnimals('hamster')); // I have a hamster 10
这里,我们创建来一个动物数组,所以条件语句可以和代码的其余部分抽象分离出来。现在,如果我们想要检查任何其他动物,我们只需要添加一个新的数组项。
我们也能在这个函数作用域外部使用这个动物数组变量来在代码中的其他任意地方重用它。这是一个编写更清晰、易理解和维护的代码的方法,不是吗?
2. 提前退出 / 提前返回
这是一个精简你的代码的非常酷的技巧。我记得当我开始专业工作时,我在第一天学习使用提前退出来编写条件。
让我们在之前的例子上添加更多的条件。用包含确定属性的对象替代简单字符串的动物。
现在的需求是:
-
如果没有动物,抛出一个异常
-
打印动物类型
-
打印动物名字
-
打印动物性别
1const printAnimalDetails = animal => { 2 let result; // declare a variable to store the final value 3 4 // condition 1: check if animal has a value 5 if (animal) { 6 7 // condition 2: check if animal has a type property 8 if (animal.type) { 9 10 // condition 3: check if animal has a name property 11 if (animal.name) { 12 13 // condition 4: check if animal has a gender property 14 if (animal.gender) { 15 result = ${animal.name} is a ${animal.gender} ${animal.type};; 16 } else { 17 result = "No animal gender"; 18 } 19 } else { 20 result = "No animal name"; 21 } 22 } else { 23 result = "No animal type"; 24 } 25 } else { 26 result = "No animal"; 27 } 28 29 return result; 30}; 31 32console.log(printAnimalDetails()); // 'No animal' 33 34console.log(printAnimalDetails({ type: "dog", gender: "female" })); // 'No animal name' 35 36console.log(printAnimalDetails({ type: "dog", name: "Lucy" })); // 'No animal gender' 37 38console.log( 39 printAnimalDetails({ type: "dog", name: "Lucy", gender: "female" }) 40); // 'Lucy is a female dog' 41
你觉得上面的代码怎么样?
它工作得很好,但是代码很长并且维护困难。如果不使用lint工具,找出闭合花括号在哪都会浪费很多时间。😄 想象如果代码有更复杂的逻辑会怎么样?大量的if..else语句。
我们能用三元运算符、&&条件等语法重构上面的功能,但让我们用多个返回语句编写更清晰的代码。
1const printAnimalDetails = ({type, name, gender } = {}) => { 2 if(!type) return 'No animal type'; 3 if(!name) return 'No animal name'; 4 if(!gender) return 'No animal gender'; 5 6// Now in this line of code, we're sure that we have an animal with all //the three properties here. 7 8 return ${name} is a ${gender} ${type}; 9} 10 11console.log(printAnimalDetails()); // 'No animal type' 12 13console.log(printAnimalDetails({ type: dog })); // 'No animal name' 14 15console.log(printAnimalDetails({ type: dog, gender: female })); // 'No animal name' 16 17console.log(printAnimalDetails({ type: dog, name: 'Lucy', gender: 'female' })); // 'Lucy is a female dog' 18
在这个重构过的版本中,也包含了解构和默认参数。默认参数确保如果我们传递undefined作为一个方法的参数,我们仍然有值可以解构,在这里它是一个空对象{}。
通常,在专业领域,代码被写在这两种方法之间。
另一个例子:
1function printVegetablesWithQuantity(vegetable, quantity) { 2 const vegetables = ['potato', 'cabbage', 'cauliflower', 'asparagus']; 3 4 // condition 1: vegetable should be present 5 if (vegetable) { 6 // condition 2: must be one of the item from the list 7 if (vegetables.includes(vegetable)) { 8 console.log(I like ${vegetable}); 9 10 // condition 3: must be large quantity 11 if (quantity >= 10) { 12 console.log('I have bought a large quantity'); 13 } 14 } 15 } else { 16 throw new Error('No vegetable from the list!'); 17 } 18} 19 20printVegetablesWithQuantity(null); // No vegetable from the list! 21printVegetablesWithQuantity('cabbage'); // I like cabbage 22printVegetablesWithQuantity('cabbage', 20); 23// 'I like cabbage 24// 'I have bought a large quantity' 25
现在,我们有:
-
1 if/else 语句过滤非法条件
-
3 级嵌套if语句 (条件 1, 2, & 3)
一个普遍遵循的规则是:在非法条件匹配时提前退出。
1function printVegetablesWithQuantity(vegetable, quantity) { 2 3 const vegetables = ['potato', 'cabbage', 'cauliflower', 'asparagus']; 4 5 // condition 1: throw error early 6 if (!vegetable) throw new Error('No vegetable from the list!'); 7 8 // condition 2: must be in the list 9 if (vegetables.includes(vegetable)) { 10 console.log(I like ${vegetable}); 11 12 // condition 3: must be a large quantity 13 if (quantity >= 10) { 14 console.log('I have bought a large quantity'); 15 } 16 } 17} 18
通过这么做,我们少了一个嵌套层级。当你有一个长的if语句时,这种代码风格特别好。
我们能通过条件倒置和提前返回,进一步减少嵌套的if语句。查看下面的条件2,观察我们是怎么做的
1function printVegetablesWithQuantity(vegetable, quantity) { 2 3 const vegetables = ['potato', 'cabbage', 'cauliflower', 'asparagus']; 4 5 if (!vegetable) throw new Error('No vegetable from the list!'); 6 // condition 1: throw error early 7 8 if (!vegetables.includes(vegetable)) return; 9 // condition 2: return from the function is the vegetable is not in 10 // the list 11 12 13 console.log(I like ${vegetable}); 14 15 // condition 3: must be a large quantity 16 if (quantity >= 10) { 17 console.log('I have bought a large quantity'); 18 } 19} 20
通过倒置条件2,代码没有嵌套语句了。这种技术在我们有很多条件并且当任何特定条件不匹配时,我们想停止进一步处理的时候特别有用。
所以,总是关注更少的嵌套和提前返回,但也不要过度地使用。
3. 用对象字面量或Map替代Switch语句
让我们来看看下面的例子,我们想要基于颜色打印水果:
1function printFruits(color) { 2 // use switch case to find fruits by color 3 switch (color) { 4 case 'red': 5 return ['apple', 'strawberry']; 6 case 'yellow': 7 return ['banana', 'pineapple']; 8 case 'purple': 9 return ['grape', 'plum']; 10 default: 11 return []; 12 } 13} 14 15printFruits(null); // [] 16printFruits('yellow'); // ['banana', 'pineapple'] 17
上面的代码没有错误,但是它仍然有些冗长。相同的功能能用对象字面量以更清晰的语法实现:
1// use object literal to find fruits by color 2 const fruitColor = { 3 red: ['apple', 'strawberry'], 4 yellow: ['banana', 'pineapple'], 5 purple: ['grape', 'plum'] 6 }; 7 8function printFruits(color) { 9 return fruitColor[color] || []; 10} 11
另外,你也能用 Map 来实现相同的功能:
1// use Map to find fruits by color 2 const fruitColor = new Map() 3 .set('red', ['apple', 'strawberry']) 4 .set('yellow', ['banana', 'pineapple']) 5 .set('purple', ['grape', 'plum']); 6 7function printFruits(color) { 8 return fruitColor.get(color) || []; 9} 10
Map 允许保存键值对,是自从ES2015以来可以使用的对象类型。
对于上面的例子,相同的功能也能用数组方法Array.filter 来实现。
1const fruits = [ 2 { name: 'apple', color: 'red' }, 3 { name: 'strawberry', color: 'red' }, 4 { name: 'banana', color: 'yellow' }, 5 { name: 'pineapple', color: 'yellow' }, 6 { name: 'grape', color: 'purple' }, 7 { name: 'plum', color: 'purple' } 8]; 9 10function printFruits(color) { 11 return fruits.filter(fruit => fruit.color === color); 12} 13
4. 默认参数和解构
当使用 JavaScript 工作时,我们总是需要检查 null/undefined 值并赋默认值,否则可能编译失败。
1function printVegetablesWithQuantity(vegetable, quantity = 1) { 2// if quantity has no value, assign 1 3 4 if (!vegetable) return; 5 console.log(We have ${quantity} ${vegetable}!); 6} 7 8//results 9printVegetablesWithQuantity('cabbage'); // We have 1 cabbage! 10printVegetablesWithQuantity('potato', 2); // We have 2 potato! 11
如果 vegetable 是一个对象呢?我们能赋一个默认参数吗?
1function printVegetableName(vegetable) { 2 if (vegetable && vegetable.name) { 3 console.log (vegetable.name); 4 } else { 5 console.log('unknown'); 6 } 7} 8 9printVegetableName(undefined); // unknown 10printVegetableName({}); // unknown 11printVegetableName({ name: 'cabbage', quantity: 2 }); // cabbage 12
在上面的例子中,如果vegetable 存在,我们想要打印 vegetable name, 否则打印"unknown"。
我们能通过使用默认参数和解构来避免条件语句 if (vegetable && vegetable.name) {} 。
1// destructing - get name property only 2// assign default empty object {} 3 4function printVegetableName({name} = {}) { 5 console.log (name || 'unknown'); 6} 7 8 9printVegetableName(undefined); // unknown 10printVegetableName({ }); // unknown 11printVegetableName({ name: 'cabbage', quantity: 2 }); // cabbage 12
因为我们只需要 name 属性,所以我们可以使用 { name } 解构参数,然后我们就能在代码中使用 name 作为变量,而不是 vegetable.name 。
我们还赋了一个空对象 {} 作为默认值,因为当执行 printVegetableName(undefined) 时会得到一个错误:不能从 undefined 或 null 解构属性 name ,因为在 undefined 中没有 name 属性。
5. 用 Array.every & Array.some 匹配全部/部分内容
我们能使用数组方法减少代码行。查看下面的代码,我们想要检查是否所有的水果都是红色的:
1const fruits = [ 2 { name: 'apple', color: 'red' }, 3 { name: 'banana', color: 'yellow' }, 4 { name: 'grape', color: 'purple' } 5 ]; 6 7function test() { 8 let isAllRed = true; 9 10 // condition: all fruits must be red 11 for (let f of fruits) { 12 if (!isAllRed) break; 13 isAllRed = (f.color == 'red'); 14 } 15 16 console.log(isAllRed); // false 17} 18
这代码太长了!我们能用 Array.every 来减少代码行数:
1const fruits = [ 2 { name: 'apple', color: 'red' }, 3 { name: 'banana', color: 'yellow' }, 4 { name: 'grape', color: 'purple' } 5 ]; 6 7function test() { 8 // condition: short way, all fruits must be red 9 const isAllRed = fruits.every(f => f.color == 'red'); 10 11 console.log(isAllRed); // false 12} 13
相似地,如果我们想测试是否有任何红色的水果,我们能用一行 Array.some 来实现它。
1const fruits = [ 2 { name: 'apple', color: 'red' }, 3 { name: 'banana', color: 'yellow' }, 4 { name: 'grape', color: 'purple' } 5]; 6 7function test() { 8 // condition: if any fruit is red 9 const isAnyRed = fruits.some(f => f.color == 'red'); 10 11 console.log(isAnyRed); // true 12} 13
6. 使用可选链和空值合并
这有两个为编写更清晰的条件语句而即将成为 JavaScript 增强的功能。当写这篇文章时,它们还没有被完全支持,你需要使用 Babel 来编译。
可选链允许我们没有明确检查中间节点是否存在地处理 tree-like 结构,空值合并和可选链组合起来工作得很好,以确保为不存在的值赋一个默认值。
这有一个例子:
1const car = { 2 model: 'Fiesta', 3 manufacturer: { 4 name: 'Ford', 5 address: { 6 street: 'Some Street Name', 7 number: '5555', 8 state: 'USA' 9 } 10 } 11} 12 13// to get the car model 14const model = car && car.model || 'default model'; 15 16// to get the manufacturer street 17const street = car && car.manufacturer && car.manufacturer.address && 18car.manufacturer.address.street || 'default street'; 19 20// request an un-existing property 21const phoneNumber = car && car.manufacturer && car.manufacturer.address 22&& car.manufacturer.phoneNumber; 23 24console.log(model) // 'Fiesta' 25console.log(street) // 'Some Street Name' 26console.log(phoneNumber) // undefined 27
所以,如果我们想要打印是否车辆生产商来自美国,代码将看起来像这样:
1const isManufacturerFromUSA = () => { 2 if(car && car.manufacturer && car.manufacturer.address && 3 car.manufacturer.address.state === 'USA') { 4 console.log('true'); 5 } 6} 7 8 9checkCarManufacturerState() // 'true' 10
你能清晰地看到当有一个更复杂的对象结构时,这能变得多乱。有一些第三方的库有它们自己的函数,像 lodash 或 idx。例如 lodash 有 _.get 方法。然而,JavaScript 语言本身被引入这个特性是非常酷的。
这展示了这些新特性如何工作:
1// to get the car model 2const model = car?.model ?? 'default model'; 3 4// to get the manufacturer street 5const street = car?.manufacturer?.address?.street ?? 'default street'; 6 7// to check if the car manufacturer is from the USA 8const isManufacturerFromUSA = () => { 9 if(car?.manufacturer?.address?.state === 'USA') { 10 console.log('true'); 11 } 12} 13
这看起来很美观并容易维护。它已经到 TC39 stage 3 阶段,让我们等待它获得批准,然后我们就能无处不在地看到这难以置信的语法的使用。
总结
让我们为了编写更清晰、易维护的代码,学习并尝试新的技巧和技术,因为在几个月后,长长的条件看起来像搬石头砸自己的脚。😄
