前言
JavaScript优化技术
1.多个条件优化
//old
if(x==='a'||x==='b'||x==='c'){
}
//shorthand
if(['a','b','c'].includes(x)){
}
2. if else
//old
if(x>5){
}else{
}
//shorthand
(x>5)?true:false
3. 空 未定义 空检查
//old
if(x!==null||x!==undefined||x!==''){
}
//shorthand
let y=x||''
4. 空合并运算符??
//如果左侧为null或未定义 则返回右侧的值
const x=null??'default'
5. 给多个变量赋值
let [x1,x2,x3]=[1,2,3]
6. 如果存在
//old
if(x===true){}
//shorthand
if(x){}
7. 多个条件的and(&&)运算符
//old
if(x){
dosomethindg()
}
//shorthand
x&&dosomething()
8. Switch 将条件保存在键值对象中,并可以根据条件使用
//old
switch (x) {
case 1:
test1();
break;
case 2:
test2();
break;
case 3:
test();
break;
// And so on...
}
//shorthand
let x={
1:x1,
2:x2,
3:x3
}
x[something]&&x[something]()
9. 隐式返回速记
//使用箭头功能,我们可以直接返回值,而不必编写return语句
something=x=>{
somthing
}
10. 小数基指数
//old
for(let i =0;i<10000;i++){}
//shorthand
for(let i=0;i<1e4;i++){}
11. 对象属性分配
//old
let x={x1:x1,x2:x2}
//shorthand
let x={x1,x2}
12. Object.entries() 将对象转换为对象数组
const data={test1:'abc',test2:'abc',test3:'abc'}
const arr=Object.entries(data)
console.log(arr)
//
/*
[
['test1':'abc'],
['test2':'abc'],
['test3':'abc'],
]
*/
13. Object.values()
const data={test1:'abc',test2:'abc',test3:'abc'}
const arr=Object.values(data)
console.log(arr)
//
/*
[
'abc','abc','abc'
]
*/
14. Double Bitwise
//old
Math.floor(1.9)===1//true
//shorthand 双重NOT按位运算符方法仅适用于32位整数
~~1.9===1//true