1// original2if(a ==='a'){3 b =true4}else{5 b =false6}7// concise8 b = a ==='a'
4、简单的if判断使⽤三元表达式
1// original2if(a ==='a'){3 b = a
4}else{5 b = c
6}7// concise8 b = a ==='a'? a : c
5、使⽤includes简化if判断
1// original2if(a ===1|| a ===2|| a ===3|| a ===4){3}5// concise6 let arr =[1,2,3,4]7if(arr.includes(a)){8}
6.使⽤some⽅法判断是否有满⾜条件的元素
1// original2 let arr =[1,3,5,7]3 function isHasNum (n){4for(let i =0; i < arr.length; i ++){5if(arr[i]=== n){6returntrue7}8}9returnfalse10}11// concise12 let arr =[1,3,5,7]13 let isHasNum = n => arr.some(num => num === n)14// best15 let arr =[1,3,5,7]16 let isHasNum =(n, arr)=> arr.some(num => num === n)
7、使⽤forEach⽅法遍历数组,不形成新数组
1// original2for(let i =0; i < arr.length; i ++){4 arr[i].key = balabala 5}6// concise7 arr.forEach(item =>{9 item.key = balabala 10})
8、使⽤filter⽅法过滤原数组,形成新数组
1// original2 let arr =[1,3,5,7],3 newArr =[]4for(let i =0; i < arr.length; i ++){5if(arr[i]>4){6 newArr.push(arr[i])7}8}9// concise10 let arr =[1,3,5,7]11 let newArr = arr.filter(n => n >4)// [5, 7]
9、使⽤map对数组中所有元素批量处理,形成新数组
1// original2 let arr =[1,3,5,7],3 let newArr =[]4for(let i =0; i < arr.length; i ++){5 newArr.push(arr[i]+1)6}7// concise8 let arr =[1,3,5,7]9 let newArr = arr.map(n => n +1)// [2, 4, 6, 8]