优化逻辑判断
刚结束一个项目,在项目开发时为了图快导致代码不优雅,现在终于有时间来优化一下我的代码了。我们都知道通常判断会使用到if、if else、swicth,那要怎么优雅的写出逻辑判断呢,我也在一步步的摸索学习。
ES6 中提供的数组新特性,也可以更轻松的处理逻辑判断。
1. 多条件判断
可能你也跟我一样,遇到多条件判断时会写出这种,但条件过多时阅读不方便
if ( i == 1 || i ==2 || 1== 3) { do sth }
我们可以使用 Array.includes方法,检查数组是否包含某个值
let arr = [ 1, 2, 3 ]
if(arr.includes(i)){
do sth
}
2.判断数组中是否所有项都满足
//全部都有苹果 let json = [ {name: '苹果' }, {name: '香蕉' }, ] function get_pg() { let is_pingguo= true; for (let f of json ) { if (!is_pingguo) break; is_pingguo= (f.name=== '苹果'); } console.log(is_pingguo); // false }
但是可以通过Array.ervey来判断
function get_pg() { const is_pingguo= json.every(f => f.name=== '苹果'); console.log(is_pingguo); // false }
3.判断是否某一项满足条件
使用Array.some来判断
const is_pingguo= json.some(f => f.name== '苹果');