昨晚听了个公开课,老师讲了几种条件语句优化方法,真不错!
- 数组方法 Array.includes
- 提前退出/提前返回
- 使用对象字面量代替switch语句
- 默认参数解构
- Array.some/Array.every
示例一:
function printAnimals(animal) {
const animals = ['dog', 'cat', 'hamster']
if (animals.includes(animal)){
console.log(animal)
}
}
printAnimals('dog')
本例中使用数组的方法来代替大量的或操作,简洁明了,每次扩展只需要给数组添加值,不需要再加if else。
示例二:
const printAnimalsDetails = ({ type, name, gender} = {}) => {
if (!type) return 'no animal type'
if (!name) return 'no animal name'
if (!gender) return 'no animal gender'
return `${name} is a ${gender} ${type}`
}
console.log(printAnimalsDetails({type:'dog', name: '',gender:'boy'}))
本示例中使用了对象的解构来进行数据校验,实现了提前退出/提前返回。
注:解构赋值语法是一种 Javascript 表达式。通过解构赋值, 可以将属性/值从对象/数组中取出,赋值给其他变量。
示例三:
const fruitsColor = new Map().set('red', ['apple']).set('yellow', ['banana'])
function printFruits(color) {
return fruitsColor.get(color) || []
}
console.log(printFruits(null))
console.log(printFruits('yellow'))
示例四:
检测数组中是否有元素大于10
function isBiggerThan10(element, index, array) {
return element > 10;
}
[2, 5, 8, 1, 4].some(isBiggerThan10); // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true
检测数组所有元素是否都大于10
function isBigEnough(element, index, array) {
return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough); // false
[12, 54, 18, 130, 44].every(isBigEnough); // true