-
当同时声明多个变量,可简写成一行
let x; let y=20; // 简写 let x,y=20;
-
巧妙使用解构赋值
let a,b,c; a=1; b=2; c=3; // 简写 let [a,b,c] =[1,2,3]
-
巧妙使用三元运算符
let num = 20; let result; if(num >=20){ result = 'hhh' }else{ result = 'xxx' } // 简写 let result = num >=20?'hhh':'xxx';
-
使用&&运算符简化if语句
if(num){ this.getDate() } // 简写 num && this.getDate()
-
单层对象的拷贝
let obj = {x:20,y:{z:30}}; const makeDeepClone = (obj) =>{ let newObject = {}; Object.keys(obj).map(key =>{ if(typeof obj[key] === 'object'){ newObject[key] = makeDeepClone(obj[key]) }else{ newObject[key] = obj[key] } }) return newObject } const cloneObj = makeDeepClone (obj); console.log(cloneObj ) // 简写 let obj = {x:20,y:{z:30}}; const cloneObj = JSON.parse(JSON.stringify(obj)) console.log(cloneObj ) // 简写 let obj = {x:20,y:{z:30}}; const cloneObj= {...obj} console.log(cloneObj )
-
数组中最大值和最小值
let arr = [1,3,4,2,0] // 简写 // 最大值 let newArr = Math.max(...arr); // 4 // 最小值 let newArr = Math.min(...arr); // 0
-
if 多条件判断
if(test === '1' || test === '2' || test === '3' ){ // 逻辑 } // 优化后 if(['1','2','3'].includes(test)){ // 逻辑处理 }
前端开发小技巧
最新推荐文章于 2024-07-04 11:38:55 发布