-
使用 Array.includes 来处理多个条件
请看下面的列子: // condition function test(fruit) { if (fruit == 'apple' || fruit == 'strawberry') { console.log('red'); } } 上面的列子看起来似乎没有什么问题。但是,如果我们还有更多的红色水果呢?是否要用 更多的 || 操作符来扩展该语句,这时可以利用 Array.includes重写上面的条件语句 function test(fruit) { // 条件提取到数组中 const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; if (redFruits.includes(fruit)) { console.log('red'); } } 将所有的可能性条件提取到一个数组中。这样,可以让代码看起来更整洁
-
减少嵌套,提前使用 return 语句
扩展前面的示例,在包含另外两个条件: 1.如果没有提供水果,抛出错误; 2.接受水果数量参数,如果超过10,则打印出相关信息; function test(fruit, quantity) { const redFruits = ['apple', 'strawberry', 'cherry', 'cranberries']; // 条件 1:fruit 必须有值 if (fruit) { // 条件 2:必须为红色 if (redFruits.includes(fruit)) { console.log('red'); // 条件 3:数量必须大于 10 if (quantity > 10) { console.log('big quantity'); } } } else { throw new Error('No fruit!'); } } // 测试结果 test(null); // 抛出错误:No fruits test('apple'); // 打印:red test('apple', 20); // 打印:red,big quantity 上面的代码,我们有: 1.1个 if/elss 语句过滤掉无效条件 2
利用ES6 编写更好的条件语句
最新推荐文章于 2023-05-15 18:23:11 发布