JavaScript中如何总结条件语句的优化策略?
- 内容介绍
- 文章标签
- 相关推荐
本文共计1809个文字,预计阅读时间需要8分钟。
对多个条件使用 Array.includes 函数进行测试如下:
javascriptfunction test(fruit) { if (fruit==='apple' || fruit==='strawberry') { console.log('red'); } // 如果还有其他红色水果需要判断,例如桃子和李子,可以继续添加条件}
对多个条件使用 Array.includes
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'); } }
我们将条件提取到一个数组中。这样做之后,代码看起来更整洁。
更少的嵌套,尽早返回
扩展前面的示例,以包含另外两个条件:
如果没有提供水果(名称),抛出错误。
如果(红色水果)数量超过 10 个,接受并打印。
本文共计1809个文字,预计阅读时间需要8分钟。
对多个条件使用 Array.includes 函数进行测试如下:
javascriptfunction test(fruit) { if (fruit==='apple' || fruit==='strawberry') { console.log('red'); } // 如果还有其他红色水果需要判断,例如桃子和李子,可以继续添加条件}
对多个条件使用 Array.includes
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'); } }
我们将条件提取到一个数组中。这样做之后,代码看起来更整洁。
更少的嵌套,尽早返回
扩展前面的示例,以包含另外两个条件:
如果没有提供水果(名称),抛出错误。
如果(红色水果)数量超过 10 个,接受并打印。

